类 com.sun.codemodel.JVar 源码实例Demo

下面列出了怎么用 com.sun.codemodel.JVar 的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Bats   文件: CodeGenMemberInjector.java

/**
 * Generated code for a class may have several class members, they
 * are initialized by invoking this method when the instance created.
 *
 * @param cg       the class generator
 * @param instance the class instance created by the compiler
 * @param context  the fragment context
 */
public static void injectMembers(ClassGenerator<?> cg, Object instance, FragmentContext context) {
  Map<Integer, Object> cachedInstances = new HashMap<>();
  for (Map.Entry<Pair<Integer, JVar>, Function<DrillBuf, ? extends ValueHolder>> setter : cg.getConstantVars().entrySet()) {
    try {
      JVar var = setter.getKey().getValue();
      Integer depth = setter.getKey().getKey();
      Object varInstance = getFieldInstance(instance, depth, cachedInstances);
      Field field = varInstance.getClass().getDeclaredField(var.name());
      field.setAccessible(true);
      field.set(varInstance, setter.getValue().apply(context.getManagedBuffer()));
    } catch (ReflectiveOperationException e) {
      throw new RuntimeException(e);
    }
  }
}
 
源代码2 项目: Bats   文件: EvaluationVisitor.java

@Override
public HoldingContainer visitFunctionHolderExpression(FunctionHolderExpression holderExpr,
    ClassGenerator<?> generator) throws RuntimeException {

  AbstractFuncHolder holder = (AbstractFuncHolder) holderExpr.getHolder();

  JVar[] workspaceVars = holder.renderStart(generator, null, holderExpr.getFieldReference());

  if (holder.isNested()) {
    generator.getMappingSet().enterChild();
  }

  HoldingContainer[] args = new HoldingContainer[holderExpr.args.size()];
  for (int i = 0; i < holderExpr.args.size(); i++) {
    args[i] = holderExpr.args.get(i).accept(this, generator);
  }

  holder.renderMiddle(generator, args, workspaceVars);

  if (holder.isNested()) {
    generator.getMappingSet().exitChild();
  }

  return holder.renderEnd(generator, args, workspaceVars, holderExpr.getFieldReference());
}
 

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;
}
 
源代码4 项目: Bats   文件: ClassGenerator.java

/**
 * declare a constant field for the class.
 * argument {@code function} holds the constant value which
 * returns a value holder must be set to the class field when the class instance created.
 * the class field innerClassField will be created if innerClassGenerator exists.
 *
 * @param prefix the prefix name of class field
 * @param t the type of class field
 * @param init init expression
 * @param function the function holds the constant value
 * @return the depth of nested class, class field
 */
public Pair<Integer, JVar> declareClassConstField(String prefix, JType t, JExpression init,
                                                  Function<DrillBuf, ? extends ValueHolder> function) {
  JVar var;
  int depth = 1;
  if (innerClassGenerator != null) {
    Pair<Integer, JVar> nested = innerClassGenerator.declareClassConstField(prefix, t, init, function);
    depth = nested.getKey() + 1;
    var = nested.getValue();
  } else {
    var = clazz.field(JMod.NONE, t, prefix + index++, init);
  }
  Pair<Integer, JVar> depthVar = Pair.of(depth, var);
  constantVars.put(depthVar, function);
  return depthVar;
}
 
源代码5 项目: Bats   文件: ClassGenerator.java

/**
 * Adds local variable declaration based on given name and type.
 *
 * @param t major type
 * @param name variable name
 * @param includeNewInstance whether to create new instance
 * @return holder instance
 */
public HoldingContainer declare(MajorType t, String name, boolean includeNewInstance) {
  JType holderType = getHolderType(t);
  JVar var;
  if (includeNewInstance) {
    var = getEvalBlock().decl(holderType, name + index, JExpr._new(holderType));
  } else {
    var = getEvalBlock().decl(holderType, name + index);
  }
  JFieldRef outputSet = null;
  if (t.getMode() == DataMode.OPTIONAL) {
    outputSet = var.ref("isSet");
  }
  index++;
  return new HoldingContainer(t, var, var.ref("value"), outputSet);
}
 

@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);
  }
}
 
源代码7 项目: Bats   文件: DrillAggFuncHolder.java

@Override
public HoldingContainer renderEnd(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables,
                                  JVar[] workspaceJVars, FieldReference fieldReference) {
  HoldingContainer out = null;
  JVar internalOutput = null;
  if (getReturnType().getMinorType() != TypeProtos.MinorType.LATE) {
    out = classGenerator.declare(getReturnType(), false);
  }
  JBlock sub = new JBlock();
  if (getReturnType().getMinorType() != TypeProtos.MinorType.LATE) {
    internalOutput = sub.decl(JMod.FINAL, classGenerator.getHolderType(getReturnType()), getReturnValue().getName(), JExpr._new(classGenerator.getHolderType(getReturnType())));
  }
  classGenerator.getEvalBlock().add(sub);
  addProtectedBlock(classGenerator, sub, output(), null, workspaceJVars, false);
  if (getReturnType().getMinorType() != TypeProtos.MinorType.LATE) {
    sub.assign(out.getHolder(), internalOutput);
  }
  //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block.
  if (!classGenerator.getMappingSet().isHashAggMapping()) {
    generateBody(classGenerator, BlockType.RESET, reset(), null, workspaceJVars, false);
  }
  generateBody(classGenerator, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false);

  return out;
}
 
源代码8 项目: apicurio-studio   文件: JaxRsEnumRule.java

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);
}
 
源代码9 项目: Bats   文件: DrillSimpleFuncHolder.java

@Override
public HoldingContainer renderEnd(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables,
                                  JVar[] workspaceJVars, FieldReference fieldReference) {
  //If the function's annotation specifies a parameter has to be constant expression, but the HoldingContainer
  //for the argument is not, then raise exception.
  for (int i = 0; i < inputVariables.length; i++) {
    if (getParameters()[i].isConstant() && !inputVariables[i].isConstant()) {
      throw new DrillRuntimeException(String.format("The argument '%s' of Function '%s' has to be constant!", getParameters()[i].getName(), this.getRegisteredNames()[0]));
    }
  }
  generateBody(classGenerator, BlockType.SETUP, setupBody(), inputVariables, workspaceJVars, true);
  HoldingContainer c = generateEvalBody(classGenerator, inputVariables, evalBody(), workspaceJVars, fieldReference);
  generateBody(classGenerator, BlockType.RESET, resetBody(), null, workspaceJVars, false);
  generateBody(classGenerator, BlockType.CLEANUP, cleanupBody(), null, workspaceJVars, false);
  return c;
}
 
源代码10 项目: jaxb2-basics   文件: EqualsArguments.java

public EqualsArguments cast(String suffix, JBlock block,
		JType jaxbElementType, boolean suppressWarnings) {
	final JVar castedLeftValue = block.decl(JMod.FINAL, jaxbElementType,
			leftValue().name() + suffix,
			JExpr.cast(jaxbElementType, leftValue()));
	if (suppressWarnings) {
		castedLeftValue.annotate(SuppressWarnings.class).param("value",
				"unchecked");
	}
	final JVar castedRightValue = block.decl(JMod.FINAL, jaxbElementType,
			rightValue().name() + suffix,
			JExpr.cast(jaxbElementType, rightValue()));
	if (suppressWarnings) {
		castedRightValue.annotate(SuppressWarnings.class).param("value",
				"unchecked");
	}
	return new EqualsArguments(getCodeModel(), castedLeftValue, JExpr.TRUE,
			castedRightValue, JExpr.TRUE);
}
 

private void generateForDirectClass(JDefinedClass traversingVisitor, JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    // add method impl to traversing visitor
    JMethod travViz;
    String visitMethodName = visitMethodNamer.apply(implClass.name());
    travViz = traversingVisitor.method(JMod.PUBLIC, returnType, visitMethodName);
    travViz._throws(exceptionType);
    JVar beanVar = travViz.param(implClass, "aBean");
    travViz.annotate(Override.class);
    JBlock travVizBloc = travViz.body();

    addTraverseBlock(travViz, beanVar, true);

    JVar retVal = travVizBloc.decl(returnType, "returnVal");

    travVizBloc.assign(retVal, JExpr.invoke(JExpr.invoke("getVisitor"), visitMethodName).arg(beanVar));

    travVizBloc._if(JExpr.ref("progressMonitor").ne(JExpr._null()))._then().invoke(JExpr.ref("progressMonitor"), "visited").arg(beanVar);

    addTraverseBlock(travViz, beanVar, false);

    travVizBloc._return(retVal);
}
 

private void processComplexType(JVar fieldSchemaVar, String name, Schema schema, Schema readerFieldSchema,
    JBlock methodBody, FieldAction action, BiConsumer<JBlock, JExpression> putExpressionIntoParent,
    Supplier<JExpression> reuseSupplier) {
  switch (schema.getType()) {
    case RECORD:
      processRecord(fieldSchemaVar, schema.getName(), schema, readerFieldSchema, methodBody, action,
          putExpressionIntoParent, reuseSupplier);
      break;
    case ARRAY:
      processArray(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    case MAP:
      processMap(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    case UNION:
      processUnion(fieldSchemaVar, name, schema, readerFieldSchema, methodBody, action, putExpressionIntoParent,
          reuseSupplier);
      break;
    default:
      throw new FastDeserializerGeneratorException("Incorrect complex type: " + action.getType());
  }
}
 
源代码13 项目: dremio-oss   文件: AggrFunctionHolder.java

@Override
public HoldingContainer renderEnd(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, JVar[]  workspaceJVars) {
  HoldingContainer out = g.declare(resolvedOutput, false);
  JBlock sub = new JBlock();
  g.getEvalBlock().add(sub);
  JVar internalOutput = sub.decl(JMod.FINAL, CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel()), getReturnName(), JExpr._new(CodeModelArrowHelper.getHolderType(resolvedOutput, g.getModel())));
  addProtectedBlock(g, sub, output(), null, workspaceJVars, false);
  sub.assign(out.getHolder(), internalOutput);
      //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block.
      if (!g.getMappingSet().isHashAggMapping()) {
        generateBody(g, BlockType.RESET, reset(), null, workspaceJVars, false);
      }
     generateBody(g, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false);

  return out;
}
 
源代码14 项目: immutable-xjc   文件: PluginImpl.java

private JExpression getUnmodifiableWrappedExpression(JCodeModel codeModel, JVar param) {
    if (param.type().erasure().equals(codeModel.ref(Collection.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableCollection").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(List.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableList").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(Map.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableMap").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(Set.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableSet").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableSortedMap").arg(param);
    } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) {
        return codeModel.ref(Collections.class).staticInvoke("unmodifiableSortedSet").arg(param);
    }
    return param;
}
 

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;
    }
}
 
源代码16 项目: immutable-xjc   文件: PluginImpl.java

private JExpression getEmptyCollectionExpression(JCodeModel codeModel, JVar param) {
    if (param.type().erasure().equals(codeModel.ref(Collection.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptyList");
    } else if (param.type().erasure().equals(codeModel.ref(List.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptyList");
    } else if (param.type().erasure().equals(codeModel.ref(Map.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptyMap");
    } else if (param.type().erasure().equals(codeModel.ref(Set.class))) {
        return codeModel.ref(Collections.class).staticInvoke("emptySet");
    } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) {
        return JExpr._new(codeModel.ref(TreeMap.class));
    } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) {
        return JExpr._new(codeModel.ref(TreeSet.class));
    }
    return param;
}
 

private void processRecord(final Schema recordSchema, JExpression recordExpr, final JBlock containerBody) {
    if (methodAlreadyDefined(recordSchema)) {
        containerBody.invoke(getMethod(recordSchema)).arg(recordExpr).arg(JExpr.direct(ENCODER));
        return;
    }
    JMethod method = createMethod(recordSchema);
    containerBody.invoke(getMethod(recordSchema)).arg(recordExpr).arg(JExpr.direct(ENCODER));

    JBlock body = method.body();
    recordExpr = method.listParams()[0];

    for (Schema.Field field : recordSchema.getFields()) {
        Schema fieldSchema = field.schema();
        if (SchemaAssistant.isComplexType(fieldSchema)) {
            JClass fieldClass = schemaAssistant.classFromSchema(fieldSchema);
            JVar containerVar = declareValueVar(field.name(), fieldSchema, body);
            JExpression valueExpression = JExpr.invoke(recordExpr, "get").arg(JExpr.lit(field.pos()));
            containerVar.init(JExpr.cast(fieldClass, valueExpression));

            processComplexType(fieldSchema, containerVar, body);
        } else {
            processSimpleType(fieldSchema, recordExpr.invoke("get").arg(JExpr.lit(field.pos())), body);
        }

    }
}
 

@SuppressWarnings("unchecked")
JBlock catchCloneNotSupported(final JBlock body, final JClass elementType) {
	final Class<? extends Cloneable> elementRuntimeClass;
	try {
		elementRuntimeClass = (Class<? extends Cloneable>) Class.forName(elementType.binaryName());
	} catch (final ClassNotFoundException e) {
		return body;
	}
	if (!cloneThrows(elementRuntimeClass)) {
		return body;
	} else {
		final JTryBlock tryBlock = body._try();
		final JCatchBlock catchBlock = tryBlock._catch(this.codeModel.ref(CloneNotSupportedException.class));
		final JVar exceptionVar = catchBlock.param("e");
		catchBlock.body()._throw(JExpr._new(this.codeModel.ref(RuntimeException.class)).arg(exceptionVar));
		return tryBlock.body();
	}
}
 
源代码19 项目: immutable-xjc   文件: PluginImpl.java

private JMethod addWithIfNotNullMethod(JDefinedClass builderClass, JFieldVar field, JMethod unconditionalWithMethod, boolean inherit) {
    if (field.type().isPrimitive())
        return null;
    String fieldName = StringUtils.capitalize(field.name());
    JMethod method = builderClass.method(JMod.PUBLIC, builderClass, "with" + fieldName + "IfNotNull");
    JVar param = generateMethodParameter(method, field);
    JBlock block = method.body();
    if (inherit) {
        generateSuperCall(method);
        method.body()._return(JExpr._this());
    } else {
        JConditional conditional = block._if(param.eq(JExpr._null()));
        conditional._then()._return(JExpr._this());
        conditional._else()._return(JExpr.invoke(unconditionalWithMethod).arg(param));
    }
    return method;
}
 
源代码20 项目: springmvc-raml-plugin   文件: PojoBuilder.java

private Map<String, JVar> getSuperParametersToAdd(JClass pojo) {
	Map<String, JVar> tFields = new LinkedHashMap<>();
	JClass parent = pojo._extends();
	if (!parent.name().equals(Object.class.getSimpleName())) {
		parent = CodeModelHelper.findFirstClassBySimpleName(this.pojoModel, parent.name());
		if (parent instanceof JDefinedClass) {
			JDefinedClass jParent = (JDefinedClass) parent;
			JMethod constructor = null;
			Iterator<JMethod> constructors = jParent.constructors();
			while (constructors.hasNext()) {
				JMethod targetConstructor = constructors.next();
				if (constructor == null || constructor.params().size() < targetConstructor.params().size()) {
					constructor = targetConstructor;
				}
			}
			for (JVar var : constructor.params()) {
				tFields.put(var.name(), var);
			}
		}
	}
	return tFields;
}
 
源代码21 项目: springmvc-raml-plugin   文件: PojoBuilder.java

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"));
}
 
源代码22 项目: dremio-oss   文件: ClassGenerator.java

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;
}
 
源代码23 项目: Bats   文件: CopyUtil.java

public static void generateCopies(ClassGenerator<?> g, VectorAccessible batch, boolean hyper){
  // we have parallel ids for each value vector so we don't actually have to deal with managing the ids at all.
  int fieldId = 0;

  JExpression inIndex = JExpr.direct("inIndex");
  JExpression outIndex = JExpr.direct("outIndex");
  for(VectorWrapper<?> vv : batch) {
    String copyMethod;
    if (!Types.isFixedWidthType(vv.getField().getType()) || Types.isRepeated(vv.getField().getType()) || Types.isComplex(vv.getField().getType())) {
      copyMethod = "copyFromSafe";
    } else {
      copyMethod = "copyFrom";
    }
    g.rotateBlock();
    JVar inVV = g.declareVectorValueSetupAndMember("incoming", new TypedFieldId(vv.getField().getType(), vv.isHyper(), fieldId));
    JVar outVV = g.declareVectorValueSetupAndMember("outgoing", new TypedFieldId(vv.getField().getType(), false, fieldId));

    if(hyper){

      g.getEvalBlock().add(
              outVV
                      .invoke(copyMethod)
                      .arg(
                              inIndex.band(JExpr.lit((int) Character.MAX_VALUE)))
                      .arg(outIndex)
                      .arg(
                              inVV.component(inIndex.shrz(JExpr.lit(16)))
                      )
      );
    }else{
      g.getEvalBlock().add(outVV.invoke(copyMethod).arg(inIndex).arg(outIndex).arg(inVV));
    }

    g.rotateBlock();
    fieldId++;
  }
}
 
源代码24 项目: jaxb2-basics   文件: HashCodeArguments.java

public HashCodeArguments element(JBlock subBlock, JType elementType) {
	final JVar elementValue = subBlock.decl(JMod.FINAL, elementType,
			value().name() + "Element", value().invoke("next"));
	final boolean isElementAlwaysSet = elementType.isPrimitive();
	final JExpression elementHasSetValue = isElementAlwaysSet ? JExpr.TRUE
			: elementValue.ne(JExpr._null());
	return spawn(elementValue, elementHasSetValue);

}
 

private void generateAccessors(final FieldOutline fieldOutline, final String propertyName, final JType returnType, final JDefinedClass declaringClass, final F1<JExpression, JVar> getMaker, final F3<JExpression, JBlock, JVar, JVar> setMaker) {
	final String constantName = getConstantName(fieldOutline);
	final JMethod getMethod = declaringClass.method(JMod.PUBLIC, returnType, "get");
	getMethod.annotate(Override.class);
	final JVar instanceParam = getMethod.param(JMod.FINAL, fieldOutline.parent().implClass, "_instance_");
	getMethod.body()._return(JOp.cond(instanceParam.eq(JExpr._null()), JExpr._null(), getMaker.f(instanceParam)));
	final JMethod setMethod = declaringClass.method(JMod.PUBLIC, void.class, "set");
	setMethod.annotate(Override.class);
	final JVar setInstanceParam = setMethod.param(JMod.FINAL, fieldOutline.parent().implClass, "_instance_");
	final JVar valueParam = setMethod.param(JMod.FINAL, returnType, "_value_");
	if (constantName == null) {
		final JConditional ifNotNull = setMethod.body()._if(setInstanceParam.ne(JExpr._null()));
		setMaker.f(ifNotNull._then(), setInstanceParam, valueParam);
	}
}
 

void generateArrayProperty(final JBlock initBody, final JVar productParam, final PropertyOutline fieldOutline, final JType elementType, final JType builderType) {
	final String fieldName = fieldOutline.getFieldName();
	final String propertyName = fieldOutline.getBaseName();
	final JType fieldType = fieldOutline.getRawType();
	final JMethod withVarargsMethod = this.builderClass.raw.method(JMod.PUBLIC, builderType, PluginContext.WITH_METHOD_PREFIX + propertyName);
	final JVar withVarargsParam = withVarargsMethod.varParam(elementType, fieldName);
	if (this.implement) {
		final JFieldVar builderField = this.builderClass.raw.field(JMod.PRIVATE, fieldType, fieldName, JExpr._null());
		withVarargsMethod.body().assign(JExpr._this().ref(builderField), withVarargsParam);
		withVarargsMethod.body()._return(JExpr._this());
		initBody.assign(productParam.ref(fieldName), JExpr._this().ref(builderField));
	}
}
 
源代码27 项目: jaxb2-basics   文件: SettersPlugin.java

@Override
public void generateSetter(FieldOutline fieldOutline,
		JDefinedClass theClass, JMethod setter, JVar value) {

	final JFieldVar field = theClass.fields().get(
			fieldOutline.getPropertyInfo().getName(false));

	if (field != null) {
		setter.body().assign(JExpr._this().ref(field), value);
	} else {
		// Fallback to the accessor
		Mode.accessor.generateSetter(fieldOutline, theClass,
				setter, value);
	}
}
 
源代码28 项目: jaxb2-basics   文件: HashCodePlugin.java

private JMethod generateObject$hashCode(final JDefinedClass theClass) {
	final JMethod object$hashCode = theClass.method(JMod.PUBLIC,
			theClass.owner().INT, "hashCode");
	object$hashCode.annotate(Override.class);
	{
		final JBlock body = object$hashCode.body();
		final JVar hashCodeStrategy = body.decl(JMod.FINAL, theClass
				.owner().ref(HashCodeStrategy2.class), "strategy",
				createHashCodeStrategy(theClass.owner()));
		body._return(JExpr._this().invoke("hashCode").arg(JExpr._null())
				.arg(hashCodeStrategy));
	}
	return object$hashCode;
}
 
源代码29 项目: hyperjaxb3   文件: SingleElementField.java

protected JMethod createSetter() {
	final MethodWriter writer = outline.createMethodWriter();

	final JMethod setter = writer.declareMethod(codeModel.VOID,
			getSetterName());
	final JVar var = writer.addParameter(exposedType, prop.getName(false));
	final JBlock block = setter.body();
	block.assign(field, var);
	block.assign(nameField, codeModel.ref(JAXBElementUtils.class)
			.staticInvoke("getName").arg(var));
	block.assign(valueField, codeModel.ref(JAXBElementUtils.class)
			.staticInvoke("getValue").arg(var));
	return setter;
}
 

static
private JInvocation createReportInvocation(JDefinedClass clazz, String operation, List<JVar> parameters, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JClass stringBuilderClazz = codeModel.ref(StringBuilder.class);

	return createReportInvocation(clazz, JExpr._new(stringBuilderClazz).arg(JExpr.lit(256)), operation, parameters, type);
}
 
 类所在包
 类方法
 同包方法