下面列出了怎么用 com.sun.codemodel.JInvocation 的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* The code generator creates a method called __DRILL_INIT__ which takes the
* place of the constructor when the code goes though the byte code merge.
* For Plain-old Java, we call the method from a constructor created for
* that purpose. (Generated code, fortunately, never includes a constructor,
* so we can create one.) Since the init block throws an exception (which
* should never occur), the generated constructor converts the checked
* exception into an unchecked one so as to not require changes to the
* various places that create instances of the generated classes.
*
* Example:<code><pre>
* public StreamingAggregatorGen1() {
* try {
* __DRILL_INIT__();
* } catch (SchemaChangeException e) {
* throw new UnsupportedOperationException(e);
* }
* }</pre></code>
*
* Note: in Java 8 we'd use the <tt>Parameter</tt> class defined in Java's
* introspection package. But, Drill prefers Java 7 which only provides
* parameter types.
*/
private void addCtor(Class<?>[] parameters) {
JMethod ctor = clazz.constructor(JMod.PUBLIC);
JBlock body = ctor.body();
// If there are parameters, need to pass them to the super class.
if (parameters.length > 0) {
JInvocation superCall = JExpr.invoke("super");
// This case only occurs for nested classes, and all nested classes
// in Drill are inner classes. Don't pass along the (hidden)
// this$0 field.
for (int i = 1; i < parameters.length; i++) {
Class<?> p = parameters[i];
superCall.arg(ctor.param(model._ref(p), "arg" + i));
}
body.add(superCall);
}
JTryBlock tryBlock = body._try();
tryBlock.body().invoke(SignatureHolder.DRILL_INIT_METHOD);
JCatchBlock catchBlock = tryBlock._catch(model.ref(SchemaChangeException.class));
catchBlock.body()._throw(JExpr._new(model.ref(UnsupportedOperationException.class)).arg(catchBlock.param("e")));
}
@Override
public JVar[] renderStart(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables, FieldReference fieldReference) {
if (!classGenerator.getMappingSet().isHashAggMapping()) { //Declare workspace vars for non-hash-aggregation.
JInvocation container = classGenerator.getMappingSet().getOutgoing().invoke("getOutgoingContainer");
complexWriter = classGenerator.declareClassField("complexWriter", classGenerator.getModel()._ref(ComplexWriter.class));
writerIdx = classGenerator.declareClassField("writerIdx", classGenerator.getModel()._ref(int.class));
lastWriterIdx = classGenerator.declareClassField("lastWriterIdx", classGenerator.getModel()._ref(int.class));
//Default name is "col", if not passed in a reference name for the output vector.
String refName = fieldReference == null ? "col" : fieldReference.getRootSegment().getPath();
JClass cwClass = classGenerator.getModel().ref(VectorAccessibleComplexWriter.class);
classGenerator.getSetupBlock().assign(complexWriter, cwClass.staticInvoke("getWriter").arg(refName).arg(container));
classGenerator.getSetupBlock().assign(writerIdx, JExpr.lit(0));
classGenerator.getSetupBlock().assign(lastWriterIdx, JExpr.lit(-1));
JVar[] workspaceJVars = declareWorkspaceVariables(classGenerator);
generateBody(classGenerator, ClassGenerator.BlockType.SETUP, setup(), null, workspaceJVars, true);
return workspaceJVars;
} else {
return super.renderStart(classGenerator, inputVariables, fieldReference);
}
}
private JVar declareSchemaVar(Schema valueSchema, String variableName, JInvocation getValueType) {
if (!useGenericTypes) {
return null;
}
if (SchemaAssistant.isComplexType(valueSchema) || Schema.Type.ENUM.equals(valueSchema.getType())) {
long schemaId = Utils.getSchemaFingerprint(valueSchema);
if (schemaVarMap.get(schemaId) != null) {
return schemaVarMap.get(schemaId);
} else {
JVar schemaVar = generatedClass.field(JMod.PRIVATE | JMod.FINAL, Schema.class,
getUniqueName(StringUtils.uncapitalize(variableName)));
constructor.body().assign(JExpr.refthis(schemaVar.name()), getValueType);
registerSchema(valueSchema, schemaId, schemaVar);
return schemaVar;
}
} else {
return null;
}
}
private void processFixed(final Schema schema, JBlock body, FieldAction action,
BiConsumer<JBlock, JExpression> putFixedIntoParent) {
if (action.getShouldRead()) {
JVar fixedBuffer = body.decl(codeModel.ref(byte[].class), getVariableName(schema.getName()))
.init(JExpr.direct(" new byte[" + schema.getFixedSize() + "]"));
body.directStatement(DECODER + ".readFixed(" + fixedBuffer.name() + ");");
JInvocation createFixed = JExpr._new(schemaAssistant.classFromSchema(schema));
if (useGenericTypes)
createFixed = createFixed.arg(getSchemaExpr(schema));
putFixedIntoParent.accept(body, createFixed.arg(fixedBuffer));
} else {
body.directStatement(DECODER + ".skipFixed(" + schema.getFixedSize() + ");");
}
}
private JVar declareSchemaVar(Schema valueSchema, String variableName, JInvocation getValueType) {
if (!useGenericTypes) {
return null;
}
if (SchemaAssistant.isComplexType(valueSchema) || Schema.Type.ENUM.equals(valueSchema.getType())) {
int schemaId = getSchemaId(valueSchema);
if (schemaVarMap.get(schemaId) != null) {
return schemaVarMap.get(schemaId);
} else {
JVar schemaVar = schemaMapMethod.body().decl(codeModel.ref(Schema.class),
getVariableName(StringUtils.uncapitalize(variableName)), getValueType);
registerSchema(valueSchema, schemaId, schemaVar);
schemaVarMap.put(schemaId, schemaVar);
return schemaVar;
}
} else {
return null;
}
}
@Override
public HoldingContainer visitFunctionHolderExpression(FunctionHolderExpression holder, ClassGenerator<?> generator) throws RuntimeException {
inc();
if (allowNewMethods && shouldNestMethod()) {
exprCount.push(0);
HoldingContainer out = generator.declare(holder.getCompleteType(), false);
JMethod setupMethod = generator.nestSetupMethod();
JMethod method = generator.innerMethod(holder.getCompleteType());
HoldingContainer returnContainer = super.visitFunctionHolderExpression(holder, generator);
method.body()._return(returnContainer.getHolder());
generator.unNestEvalBlock();
generator.unNestSetupBlock();
JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
generator.getEvalBlock().assign(out.getHolder(), methodCall);
generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));
exprCount.pop();
return out;
}
return super.visitFunctionHolderExpression(holder, generator);
}
@Override
public HoldingContainer visitIfExpression(IfExpression ifExpr, ClassGenerator<?> generator) throws RuntimeException {
inc();
if (shouldNestMethod()) {
exprCount.push(0);
HoldingContainer out = generator.declare(ifExpr.getCompleteType(), false);
JMethod setupMethod = generator.nestSetupMethod();
JMethod method = generator.innerMethod(ifExpr.getCompleteType());
HoldingContainer returnContainer = super.visitIfExpression(ifExpr, generator);
method.body()._return(returnContainer.getHolder());
generator.unNestEvalBlock();
generator.unNestSetupBlock();
JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
generator.getEvalBlock().assign(out.getHolder(), methodCall);
generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));
exprCount.pop();
return out;
}
return super.visitIfExpression(ifExpr, generator);
}
@Override
public HoldingContainer visitBooleanOperator(BooleanOperator call, ClassGenerator<?> generator) throws RuntimeException {
inc();
if (shouldNestMethod()) {
exprCount.push(0);
HoldingContainer out = generator.declare(call.getCompleteType(), false);
JMethod setupMethod = generator.nestSetupMethod();
JMethod method = generator.innerMethod(call.getCompleteType());
HoldingContainer returnContainer = super.visitBooleanOperator(call, generator);
method.body()._return(returnContainer.getHolder());
generator.unNestEvalBlock();
generator.unNestSetupBlock();
JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
generator.getEvalBlock().assign(out.getHolder(), methodCall);
generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));
exprCount.pop();
return out;
}
return super.visitBooleanOperator(call, generator);
}
@Override
public HoldingContainer visitConvertExpression(ConvertExpression e, ClassGenerator<?> generator) throws RuntimeException {
inc();
if (shouldNestMethod()) {
exprCount.push(0);
HoldingContainer out = generator.declare(e.getCompleteType(), false);
JMethod setupMethod = generator.nestSetupMethod();
JMethod method = generator.innerMethod(e.getCompleteType());
HoldingContainer returnContainer = super.visitConvertExpression(e, generator);
method.body()._return(returnContainer.getHolder());
generator.unNestEvalBlock();
generator.unNestSetupBlock();
JInvocation methodCall = generator.invokeInnerMethod(method, BlockType.EVAL);
generator.getEvalBlock().assign(out.getHolder(), methodCall);
generator.getSetupBlock().add(generator.invokeInnerMethod(setupMethod, BlockType.SETUP));
exprCount.pop();
return out;
}
return super.visitConvertExpression(e, generator);
}
public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) {
final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId);
final Class<?> valueVectorClass = fieldId.getIntermediateClass();
final JClass vvClass = model.ref(valueVectorClass);
final JClass retClass = fieldId.isHyperReader() ? vvClass.array() : vvClass;
final JVar vv = declareClassField("vv", retClass);
final JBlock b = getSetupBlock();
int[] fieldIndices = fieldId.getFieldIds();
JInvocation invoke = model.ref(VectorResolver.class).staticInvoke(fieldId.isHyperReader() ? "hyper" : "simple")
.arg(batchName)
.arg(vvClass.dotclass());
for(int i = 0; i < fieldIndices.length; i++){
invoke.arg(JExpr.lit(fieldIndices[i]));
}
// we have to cast here since Janino doesn't handle generic inference well.
JExpression casted = JExpr.cast(retClass, invoke);
b.assign(vv, casted);
vvDeclaration.put(setup, vv);
return vv;
}
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);
JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
JVar valueParam = fromValue.param(backingType, "value");
JBlock body = fromValue.body();
JVar constant = body.decl(_enum, "constant");
constant.init(quickLookupMap.invoke("get").arg(valueParam));
JConditional _if = body._if(constant.eq(JExpr._null()));
JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class));
JExpression expr = valueParam;
// if string no need to add ""
if(!isString(backingType)){
expr = expr.plus(JExpr.lit(""));
}
illegalArgumentException.arg(expr);
_if._then()._throw(illegalArgumentException);
_if._else()._return(constant);
ruleFactory.getAnnotator().enumCreatorMethod(_enum, fromValue);
}
private JInvocation appendFieldsToString(Map<String, JFieldVar> nonTransientAndNonStaticFields, JClass toStringBuilderRef) {
JInvocation invocation = JExpr._new(toStringBuilderRef).arg(JExpr._this());
Iterator<Map.Entry<String, JFieldVar>> iterator = nonTransientAndNonStaticFields.entrySet().iterator();
if (!this.pojo._extends().name().equals(Object.class.getSimpleName())) { // If
// this
// POJO
// has
// a
// superclass,
// append
// the
// superclass
// toString()
// method.
invocation = invocation.invoke("appendSuper").arg(JExpr._super().invoke("toString"));
}
while (iterator.hasNext()) {
Map.Entry<String, JFieldVar> pair = iterator.next();
invocation = invocation.invoke("append").arg(JExpr.lit(pair.getKey())).arg(pair.getValue());
}
return invocation;
}
private JInvocation appendFieldsToHashCode(Map<String, JFieldVar> nonTransientAndNonStaticFields, JClass hashCodeBuilderRef) {
JInvocation invocation = JExpr._new(hashCodeBuilderRef);
Iterator<Map.Entry<String, JFieldVar>> iterator = nonTransientAndNonStaticFields.entrySet().iterator();
if (!this.pojo._extends().name().equals(Object.class.getSimpleName())) { // If
// this
// POJO
// has
// a
// superclass,
// append
// the
// superclass
// hashCode()
// method.
invocation = invocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode"));
}
while (iterator.hasNext()) {
Map.Entry<String, JFieldVar> pair = iterator.next();
invocation = invocation.invoke("append").arg(pair.getValue());
}
return invocation;
}
private void withEquals() {
JMethod equals = this.pojo.method(JMod.PUBLIC, boolean.class, "equals");
JVar otherObject = equals.param(Object.class, "other");
Class<?> equalsBuilderClass = org.apache.commons.lang3.builder.EqualsBuilder.class;
if (!Config.getPojoConfig().isUseCommonsLang3()) {
equalsBuilderClass = org.apache.commons.lang.builder.EqualsBuilder.class;
}
JBlock body = equals.body();
body._if(otherObject.eq(JExpr._null()))._then()._return(JExpr.FALSE);
body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE);
body._if(JExpr._this().invoke("getClass").ne(otherObject.invoke("getClass")))._then()._return(JExpr.FALSE);
JVar otherObjectVar = body.decl(this.pojo, "otherObject").init(JExpr.cast(this.pojo, otherObject));
JClass equalsBuilderRef = this.pojo.owner().ref(equalsBuilderClass);
JInvocation equalsBuilderInvocation = appendFieldsToEquals(getNonTransientAndNonStaticFields(), otherObjectVar, equalsBuilderRef);
body._return(equalsBuilderInvocation.invoke("isEquals"));
}
private JInvocation appendFieldsToEquals(Map<String, JFieldVar> nonTransientAndNonStaticFields, JVar otherObject,
JClass equalsBuilderRef) {
JInvocation invocation = JExpr._new(equalsBuilderRef);
Iterator<Map.Entry<String, JFieldVar>> iterator = nonTransientAndNonStaticFields.entrySet().iterator();
if (!this.pojo._extends().name().equals(Object.class.getSimpleName())) {// If
// this
// POJO
// has
// a
// superclass,
// append
// the
// superclass
// equals()
// method.
invocation = invocation.invoke("appendSuper").arg(JExpr._super().invoke("equals").arg(otherObject));
}
while (iterator.hasNext()) {
Map.Entry<String, JFieldVar> pair = iterator.next();
invocation = invocation.invoke("append").arg(pair.getValue()).arg(otherObject.ref(pair.getKey()));
}
return invocation;
}
static
private JInvocation createSuperInvocation(JDefinedClass clazz, JMethod method){
JInvocation invocation;
if(method.type() != null){
invocation = JExpr._super().invoke(method.name());
} else
{
invocation = JExpr.invoke("super");
}
List<JVar> parameters = method.params();
for(JVar parameter : parameters){
invocation.arg(parameter);
}
return invocation;
}
private JMethod addAddMethod(JDefinedClass builderClass, JFieldVar field, boolean inherit) {
List<JClass> typeParams = ((JClass) getJavaType(field)).getTypeParameters();
if (!typeParams.iterator().hasNext()) {
return null;
}
JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "add" + StringUtils.capitalize(field.name()));
JBlock block = method.body();
String fieldName = field.name();
JVar param = method.param(JMod.FINAL, typeParams.iterator().next(), fieldName);
if (inherit) {
generateSuperCall(method);
} else {
JInvocation invocation = JExpr.refthis(fieldName).invoke("add").arg(param);
block.add(invocation);
}
block._return(JExpr._this());
return method;
}
@Override
void generateCode(ClassGenerator<WindowFramer> cg) {
final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup");
final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping);
cg.setMappingSet(mappingSet);
final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId);
final JExpression outIndex = cg.getMappingSet().getValueWriteIndex();
JInvocation setMethod = vv.invoke("getMutator").invoke("setSafe").arg(outIndex).arg(JExpr.direct("partition." + getName()));
cg.getEvalBlock().add(setMethod);
}
@Override
void generateCode(ClassGenerator<WindowFramer> cg) {
final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup");
final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping);
cg.setMappingSet(mappingSet);
final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId);
final JExpression outIndex = cg.getMappingSet().getValueWriteIndex();
JInvocation setMethod = vv.invoke("getMutator").invoke("setSafe").arg(outIndex)
.arg(JExpr.direct("partition.ntile(" + numTiles + ")"));
cg.getEvalBlock().add(setMethod);
}
private HoldingContainer visitValueVectorWriteExpression(ValueVectorWriteExpression e, ClassGenerator<?> generator) {
final LogicalExpression child = e.getChild();
final HoldingContainer inputContainer = child.accept(this, generator);
JBlock block = generator.getEvalBlock();
JExpression outIndex = generator.getMappingSet().getValueWriteIndex();
JVar vv = generator.declareVectorValueSetupAndMember(generator.getMappingSet().getOutgoing(), e.getFieldId());
// Only when the input is a reader, use writer interface to copy value.
// Otherwise, input is a holder and we use vv mutator to set value.
if (inputContainer.isReader()) {
JType writerImpl = generator.getModel()._ref(
TypeHelper.getWriterImpl(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
JType writerIFace = generator.getModel()._ref(
TypeHelper.getWriterInterface(inputContainer.getMinorType(), inputContainer.getMajorType().getMode()));
JVar writer = generator.declareClassField("writer", writerIFace);
generator.getSetupBlock().assign(writer, JExpr._new(writerImpl).arg(vv).arg(JExpr._null()));
generator.getEvalBlock().add(writer.invoke("setPosition").arg(outIndex));
String copyMethod = inputContainer.isSingularRepeated() ? "copyAsValueSingle" : "copyAsValue";
generator.getEvalBlock().add(inputContainer.getHolder().invoke(copyMethod).arg(writer));
if (e.isSafe()) {
HoldingContainer outputContainer = generator.declare(Types.REQUIRED_BIT);
generator.getEvalBlock().assign(outputContainer.getValue(), JExpr.lit(1));
return outputContainer;
}
} else {
final JInvocation setMeth = GetSetVectorHelper.write(e.getChild().getMajorType(), vv, inputContainer, outIndex, e.isSafe() ? "setSafe" : "set");
if (inputContainer.isOptional()) {
JConditional jc = block._if(inputContainer.getIsSet().eq(JExpr.lit(0)).not());
block = jc._then();
}
block.add(setMeth);
}
return null;
}
public JExpression getFixedValue(Schema schema, JExpression fixedBytesExpr, JInvocation getSchemaExpr) {
if (!useGenericTypes) {
return JExpr._new(codeModel.ref(schema.getFullName())).arg(fixedBytesExpr);
} else {
return JExpr._new(codeModel.ref(GenericData.Fixed.class)).arg(getSchemaExpr).arg(fixedBytesExpr);
}
}
public JExpression getEnumValueByName(Schema enumSchema, JExpression nameExpr, JInvocation getSchemaExpr) {
if (useGenericTypes) {
return JExpr._new(codeModel.ref(GenericData.EnumSymbol.class)).arg(getSchemaExpr).arg(nameExpr);
} else {
return codeModel.ref(enumSchema.getFullName()).staticInvoke("valueOf").arg(nameExpr);
}
}
public JExpression getEnumValueByIndex(Schema enumSchema, JExpression indexExpr, JInvocation getSchemaExpr) {
if (useGenericTypes) {
return JExpr._new(codeModel.ref(GenericData.EnumSymbol.class)).arg(getSchemaExpr)
.arg(getSchemaExpr.invoke("getEnumSymbols").invoke("get").arg(indexExpr));
} else {
return codeModel.ref(enumSchema.getFullName()).staticInvoke("values").component(indexExpr);
}
}
public JExpression getFixedValue(Schema schema, JExpression fixedBytesExpr, JInvocation getSchemaExpr) {
if (!useGenericTypes) {
return JExpr._new(codeModel.ref(schema.getFullName())).arg(fixedBytesExpr);
} else {
return JExpr._new(codeModel.ref(GenericData.Fixed.class)).arg(getSchemaExpr).arg(fixedBytesExpr);
}
}
@SuppressWarnings("unchecked")
ClassGenerator(CodeGenerator<T> codeGenerator, MappingSet mappingSet, SignatureHolder signature, EvaluationVisitor eval, JDefinedClass clazz, JCodeModel model) throws JClassAlreadyExistsException {
this.codeGenerator = codeGenerator;
this.clazz = clazz;
this.mappings = mappingSet;
this.sig = signature;
this.evaluationVisitor = eval;
this.model = Preconditions.checkNotNull(model, "Code model object cannot be null.");
blocks = new LinkedList[sig.size()];
for (int i =0; i < sig.size(); i++) {
blocks[i] = Lists.newLinkedList();
}
rotateBlock();
for (SignatureHolder child : signature.getChildHolders()) {
final String innerClassName = child.getSignatureClass().getSimpleName();
final JDefinedClass innerClazz;
// we need to extend the template class and avoid using static inner classes.
innerClazz = clazz._class(JMod.FINAL, innerClassName)._extends(child.getSignatureClass());
// we also need to delegate any inner class constructors.
for(Constructor<?> c : child.getSignatureClass().getDeclaredConstructors()){
final Class<?>[] params = c.getParameterTypes();
JMethod constructor = innerClazz.constructor(JMod.PUBLIC);
JBlock block = constructor.body();
JInvocation invoke = block.invoke("super");
block.invoke(SignatureHolder.INIT_METHOD);
// start at 1 since first parameter is the parent class
for (int i = 1; i < params.length; i++) {
constructor.param(params[i], "arg" + i);
invoke.arg(JExpr.direct("arg" + i));
}
}
innerClasses.put(innerClassName, new ClassGenerator<>(codeGenerator, mappingSet, child, eval, innerClazz, model));
}
}
public JInvocation invokeInnerMethod(JMethod method, BlockType blockType) {
JInvocation invocation = JExpr.invoke(method);
String methodName = getCurrentMapping().getMethodName(blockType);
CodeGeneratorMethod cgm = sig.get(sig.get(methodName));
for (CodeGeneratorArgument arg : cgm) {
invocation.arg(JExpr.ref(arg.getName()));
}
return invocation;
}
@Override
void generateCode(ClassGenerator<WindowFramer> cg) {
final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup");
final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping);
cg.setMappingSet(mappingSet);
final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId);
final JExpression outIndex = cg.getMappingSet().getValueWriteIndex();
JInvocation setMethod = vv.invoke("setSafe").arg(outIndex).arg(JExpr.direct("partition." + getName()));
cg.getEvalBlock().add(setMethod);
}
@Override
void generateCode(ClassGenerator<WindowFramer> cg) {
final GeneratorMapping mapping = GeneratorMapping.create("setupPartition", "outputRow", "resetValues", "cleanup");
final MappingSet mappingSet = new MappingSet(null, "outIndex", mapping, mapping);
cg.setMappingSet(mappingSet);
final JVar vv = cg.declareVectorValueSetupAndMember(cg.getMappingSet().getOutgoing(), fieldId);
final JExpression outIndex = cg.getMappingSet().getValueWriteIndex();
JInvocation setMethod = vv.invoke("setSafe").arg(outIndex)
.arg(JExpr.direct("partition.ntile(" + numTiles + ")"));
cg.getEvalBlock().add(setMethod);
}
private JInvocation getUDFInstance(JCodeModel m) {
if (isGenericUDF) {
return JExpr._new(m.directClass(genericUdfClazz.getCanonicalName()));
} else {
return JExpr._new(m.directClass(GenericUDFBridge.class.getCanonicalName()))
.arg(JExpr.lit(udfName))
.arg(JExpr.lit(false))
.arg(JExpr.lit(udfClazz.getCanonicalName().toString()));
}
}
@Test
public void testClassWithoutPersistenceContextField() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
ruleField.annotate(Rule.class);
final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
ruleField.init(instance);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
try {
// WHEN
new JpaUnitRule(cut);
fail("IllegalArgumentException expected");
} catch (final IllegalArgumentException e) {
// THEN
assertThat(e.getMessage(), containsString("EntityManagerFactory or EntityManager field annotated"));
}
}