Java Code Examples for com.sun.codemodel.JDefinedClass#method()

The following examples show how to use com.sun.codemodel.JDefinedClass#method() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DeepCopyGenerator.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
JMethod generateCreateCopyMethod(final boolean partial) {
	final JDefinedClass definedClass = this.classOutline.implClass;

	final JMethod cloneMethod = definedClass.method(JMod.PUBLIC, definedClass, this.pluginContext.copyMethodName);
	final CopyGenerator cloneGenerator = this.pluginContext.createCopyGenerator(cloneMethod, partial);
	cloneMethod.annotate(Override.class);

	final JBlock body = cloneMethod.body();

	final JVar newObjectVar;
	final boolean superPartialCopyable = this.pluginContext.partialCopyableInterface.isAssignableFrom(definedClass._extends());
	final boolean superCopyable = this.pluginContext.copyableInterface.isAssignableFrom(definedClass._extends());
	if (superPartialCopyable) {
		newObjectVar = body.decl(JMod.FINAL, definedClass, this.pluginContext.newObjectVarName, JExpr.cast(definedClass, cloneGenerator.generatePartialArgs(this.pluginContext.invoke(JExpr._super(), this.pluginContext.copyMethodName))));
	} else if(superCopyable) {
		newObjectVar = body.decl(JMod.FINAL, definedClass, this.pluginContext.newObjectVarName, JExpr.cast(definedClass, JExpr._super().invoke(this.pluginContext.copyMethodName)));
	} else {
		newObjectVar = body.decl(JMod.FINAL, definedClass, this.pluginContext.newObjectVarName, null);
		final JBlock maybeTryBlock = this.pluginContext.catchCloneNotSupported(body, definedClass._extends());
		maybeTryBlock.assign(newObjectVar, JExpr.cast(definedClass, JExpr._super().invoke(this.pluginContext.cloneMethodName)));
	}
	generateFieldCopyExpressions(cloneGenerator, body, newObjectVar, JExpr._this());
	body._return(newObjectVar);
	return cloneMethod;
}
 
Example 2
Source File: BoundPropertiesPlugin.java    From jaxb2-rich-contract-plugin with MIT License 6 votes vote down vote up
private JMethod generateLazyProxyInitGetter(final ClassOutline classOutline, final FieldOutline fieldOutline) {
	final JCodeModel m = classOutline.parent().getCodeModel();
	final JDefinedClass definedClass = classOutline.implClass;
	final String fieldName = fieldOutline.getPropertyInfo().getName(false);
	final String getterName = "get" + fieldOutline.getPropertyInfo().getName(true);
	final JFieldVar collectionField = definedClass.fields().get(fieldName);
	final JClass elementType = ((JClass) collectionField.type()).getTypeParameters().get(0);
	final JClass proxyFieldType = m.ref(BoundList.class).narrow(elementType);
	final JFieldRef collectionFieldRef = JExpr._this().ref(collectionField);
	final JFieldRef proxyField = JExpr._this().ref(collectionField.name() + BoundPropertiesPlugin.PROXY_SUFFIX);
	final JMethod oldGetter = definedClass.getMethod(getterName, new JType[0]);
	definedClass.methods().remove(oldGetter);
	final JMethod newGetter = definedClass.method(JMod.PUBLIC, proxyFieldType, getterName);
	newGetter.body()._if(collectionFieldRef.eq(JExpr._null()))._then().assign(collectionFieldRef, JExpr._new(m.ref(ArrayList.class).narrow(elementType)));
	final JBlock ifProxyNull = newGetter.body()._if(proxyField.eq(JExpr._null()))._then();
	ifProxyNull.assign(proxyField, JExpr._new(m.ref(BoundListProxy.class).narrow(elementType)).arg(collectionFieldRef));
	newGetter.body()._return(proxyField);
	return newGetter;
}
 
Example 3
Source File: CreateTraversingVisitorClass.java    From jaxb-visitor with Apache License 2.0 6 votes vote down vote up
private void generate(JDefinedClass traversingVisitor, JTypeVar returnType, JTypeVar exceptionType, JClass implClass) {
    // add method impl to traversing visitor
    JMethod travViz;
    travViz = traversingVisitor.method(JMod.PUBLIC, returnType, visitMethodNamer.apply(implClass.name()));
    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(beanVar, "accept").arg(JExpr.invoke("getVisitor")));
    travVizBloc._if(JExpr.ref("progressMonitor").ne(JExpr._null()))._then().invoke(JExpr.ref("progressMonitor"), "visited").arg(beanVar);

    // case to traverse after the visit
    addTraverseBlock(travViz, beanVar, false);
    travVizBloc._return(retVal);
}
 
Example 4
Source File: ImplementationBuilder.java    From aem-component-generator with Apache License 2.0 5 votes vote down vote up
private void addExportedTypeMethod(JDefinedClass jc) {
    if (this.isAllowExporting) {
        JFieldVar jFieldVar = jc.field(PRIVATE, codeModel.ref(Resource.class), "resource");
        jFieldVar.annotate(codeModel.ref(SlingObject.class));
        JMethod method = jc.method(JMod.PUBLIC, codeModel.ref(String.class), "getExportedType");
        method.annotate(codeModel.ref(Override.class));
        method.body()._return(jFieldVar.invoke("getResourceType"));
    }
}
 
Example 5
Source File: DelegatingMethodBodyRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyRule_onNullFieldName_shouldFallBackToDefaultFieldName() throws JClassAlreadyExistsException {

	rule = new DelegatingMethodBodyRule(null);

	JDefinedClass jClass = jCodeModel.rootPackage()._class(JMod.PUBLIC, "TestClass");
	JMethod jMethod = jClass.method(JMod.PUBLIC, Object.class, "getBase");
	jMethod = rule.apply(getEndpointMetadata(), CodeModelHelper.ext(jMethod, jClass.owner()));

	assertThat(jMethod, is(notNullValue()));
	assertThat(jMethod.body().isEmpty(), is(false));
	assertThat(jMethod.params(), hasSize(0));
	assertThat(serializeModel(), containsString("return this.delegate.getBase();"));
}
 
Example 6
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testJpaUnitRunnerAndJpaUnitRuleFieldExcludeEachOther() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    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 JpaUnitRunner(cut);
        fail("InitializationError expected");
    } catch (final InitializationError e) {
        // expected
        assertThat(e.getCauses().get(0).getMessage(), containsString("exclude each other"));
    }

}
 
Example 7
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithMultiplePersistenceContextFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar em1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em1");
    em1Field.annotate(PersistenceContext.class);
    final JFieldVar em2Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em2");
    em2Field.annotate(PersistenceContext.class);
    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());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(), containsString("Only single field is allowed"));
}
 
Example 8
Source File: ImplementMeMethodBodyRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyMethodRule_shouldCreate_validMethodSignature_withBody() throws JClassAlreadyExistsException {

	JDefinedClass jClass = jCodeModel.rootPackage()._class("TestController");
	JMethod jMethod = jClass.method(JMod.PUBLIC, ResponseEntity.class, "getBase");
	jMethod = rule.apply(getEndpointMetadata(), CodeModelHelper.ext(jMethod, jClass.owner()));

	assertThat(jMethod.body().isEmpty(), is(false));
	assertThat(serializeModel(), containsString("return null; //TODO Autogenerated Method Stub. Implement me please."));
}
 
Example 9
Source File: PluginImpl.java    From xero-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Update getters to use Java List. For example:
 * ArrayOfInvoices getInvoices() -> List<Invoice> getInvoices()
 */
private void updateArrayOfGetters(ClassOutline co, JCodeModel model) {
  JDefinedClass implClass = co.implClass;

  List<JMethod> removedMethods = new ArrayList<>();
  Iterator<JMethod> iter = implClass.methods().iterator();
  while (iter.hasNext()) {
    JMethod method = iter.next();
    if (method.type().name().startsWith("ArrayOf")) {
      removedMethods.add(method);
      iter.remove();
    }
  }

  for (JMethod removed : removedMethods) {
    // Parse the old code to get the variable name
    StringWriter oldWriter = new StringWriter();
    removed.body().state(new JFormatter(oldWriter));
    String oldBody = oldWriter.toString();
    String varName = oldBody.substring(oldBody.indexOf("return ") + "return ".length(), oldBody.indexOf(";"));

    // Build the new method
    JClass newReturnType = (JClass) ((JDefinedClass) removed.type()).fields().values().iterator().next().type();
    JMethod newMethod = implClass.method(removed.mods().getValue(), newReturnType, removed.name());
    JFieldVar field = implClass.fields().get(varName);          
    JClass typeParameter = newReturnType.getTypeParameters().get(0);
    String fieldName = model._getClass(field.type().fullName()).fields().keySet().iterator().next();

    newMethod.body()._return(
        JOp.cond(field.eq(JExpr._null()),
            JExpr._new(model.ref("java.util.ArrayList").narrow(typeParameter)),
            field.invoke("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1))));
  }    
}
 
Example 10
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextFieldOfWrongType() 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 JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "em");
    emField.annotate(PersistenceContext.class);
    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("annotated with @PersistenceContext is not of type EntityManager"));
    }
}
 
Example 11
Source File: PMMLPlugin.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static
private void createGetterProxy(JDefinedClass beanClazz, JType type, String name, String getterName){
	JMethod getterMethod = beanClazz.getMethod(getterName, new JType[0]);

	JMethod method = beanClazz.method(JMod.PUBLIC, type, name);
	method.annotate(Override.class);

	method.body()._return(JExpr.invoke(getterMethod));

	moveBefore(beanClazz, method, getterMethod);
}
 
Example 12
Source File: DelegatingMethodBodyRuleTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void applyRuleOnParametrizedEndpoint_shouldCreate_methodCall_onDelegate() throws JClassAlreadyExistsException {

	JDefinedClass jClass = jCodeModel.rootPackage()._class(JMod.PUBLIC, "TestClass");
	JMethod jMethod = jClass.method(JMod.PUBLIC, Object.class, "getBaseById");
	jMethod.param(String.class, "id");
	jMethod = rule.apply(getEndpointMetadata(2), CodeModelHelper.ext(jMethod, jClass.owner()));

	assertThat(jMethod, is(notNullValue()));
	assertThat(jMethod.body().isEmpty(), is(false));
	assertThat(jMethod.params(), hasSize(1));
	assertThat(serializeModel(), containsString("return this.controllerDelegate.getBaseById(id);"));
}
 
Example 13
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createAggregationMethod(JDefinedClass clazz, JClass valueClazz, String name, JExpression valueExpression, String operation, JPrimitiveType type){
	JMethod method = clazz.method(JMod.PUBLIC, valueClazz, name);
	method.annotate(Override.class);

	JBlock body = method.body();

	body._return(JExpr._new(valueClazz).arg(valueExpression).arg(JExpr.invoke("newReport")).arg(createReportInvocation(clazz, operation, Collections.emptyList(), type)));
}
 
Example 14
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNamesOfIdPropertiesFromAClassHierarchyHavingAMethodAnnotatedWithEmbeddedId() throws Exception {
    // GIVEN
    final String simpleClassNameBase = "EntityClass";
    final String simpleClassNameB = "SubEntityClass";
    final String compositeIdPropertyName = "compositeKey";
    final String id1PropertyName = "key1";
    final String id2PropertyName = "key2";

    final JPackage jp = jCodeModel.rootPackage();

    final JDefinedClass jIdTypeClass = jp._class(JMod.PUBLIC, "IdType");
    jIdTypeClass.annotate(Embeddable.class);
    jIdTypeClass.field(JMod.PRIVATE, Integer.class, id1PropertyName);
    jIdTypeClass.field(JMod.PRIVATE, String.class, id2PropertyName);

    final JDefinedClass jBaseClass = jp._class(JMod.PUBLIC, simpleClassNameBase);
    jBaseClass.annotate(Entity.class);
    jBaseClass.annotate(Inheritance.class).param("strategy", InheritanceType.TABLE_PER_CLASS);
    final JMethod method = jBaseClass.method(JMod.PUBLIC, jIdTypeClass, "getCompositeKey");
    method.annotate(EmbeddedId.class);
    method.body()._return(JExpr._null());

    final JDefinedClass jSubclass = jp._class(JMod.PUBLIC, simpleClassNameB)._extends(jBaseClass);
    jSubclass.annotate(Entity.class);

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> entityClass = loadClass(testFolder.getRoot(), jSubclass.name());

    // WHEN
    final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass);

    // THEN
    assertThat(namesOfIdProperties.size(), equalTo(2));
    assertThat(namesOfIdProperties,
            hasItems(compositeIdPropertyName + "." + id1PropertyName, compositeIdPropertyName + "." + id2PropertyName));
}
 
Example 15
Source File: SettersPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void generateSetters(ClassOutline classOutline,
		JDefinedClass theClass) {

	final FieldOutline[] declaredFields = FieldOutlineUtils.filter(
			classOutline.getDeclaredFields(), getIgnoring());

	for (final FieldOutline fieldOutline : declaredFields) {

		final String publicName = fieldOutline.getPropertyInfo().getName(
				true);

		final String getterName = "get" + publicName;

		final JMethod getter = theClass.getMethod(getterName, ABSENT);

		if (getter != null) {
			final JType type = getter.type();
			final JType rawType = fieldOutline.getRawType();
			final String setterName = "set" + publicName;
			final JMethod boxifiedSetter = theClass.getMethod(setterName,
					new JType[] { rawType.boxify() });
			final JMethod unboxifiedSetter = theClass.getMethod(setterName,
					new JType[] { rawType.unboxify() });
			final JMethod setter = boxifiedSetter != null ? boxifiedSetter
					: unboxifiedSetter;

			if (setter == null) {
				final JMethod generatedSetter = theClass.method(
						JMod.PUBLIC, theClass.owner().VOID, setterName);
				final JVar value = generatedSetter.param(type, "value");

				mode.generateSetter(fieldOutline, theClass,
						generatedSetter, value);
			}
		}
	}
}
 
Example 16
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 4 votes vote down vote up
@Test
public void testClassWithPersistenceContextWithWithOverwrittenConfiguration() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JAnnotationArrayMember propArray = jAnnotation.paramArray("properties");
    propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.url").param("value",
            "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.driver").param("value", "org.h2.Driver");
    propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.password").param("value", "test");
    propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.user").param("value", "test");
    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());
    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class);
    verify(listener).testStarted(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));

    verify(listener).testFinished(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
}
 
Example 17
Source File: ImmutableJaxbGenerator.java    From rice with Educational Community License v2.0 4 votes vote down vote up
private void renderBuilderDefaultCreate(JDefinedClass builderClass, JClass literalBuilderClass) {
	JMethod createMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create");
	JBlock createMethodBody = createMethod.body();
	createMethodBody.directStatement("// TODO modify as needed to pass any required values and add them to the signature of the 'create' method");
	createMethodBody.directStatement("return new Builder();");
}
 
Example 18
Source File: SimpleToStringPlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected JMethod generateToString$appendFields(ClassOutline classOutline,
		final JDefinedClass theClass) {
	final JCodeModel codeModel = theClass.owner();

	final JMethod toString$appendFields = theClass.method(JMod.PUBLIC,
			codeModel.ref(StringBuilder.class), "appendFields");
	toString$appendFields.annotate(Override.class);
	{
		final JVar locator = toString$appendFields.param(
				ObjectLocator.class, "locator");
		final JVar buffer = toString$appendFields.param(
				StringBuilder.class, "buffer");
		final JVar toStringStrategy = toString$appendFields.param(
				ToStringStrategy2.class, "strategy");
		final JBlock body = toString$appendFields.body();

		final Boolean superClassImplementsToString = StrategyClassUtils
				.superClassImplements(classOutline, ignoring,
						ToString2.class);

		if (superClassImplementsToString == null) {
			// No superclass
		} else if (superClassImplementsToString.booleanValue()) {
			body.invoke(JExpr._super(), "appendFields").arg(locator)
					.arg(buffer).arg(toStringStrategy);
		} else {
			// Superclass does not implement ToString
		}

		final FieldOutline[] declaredFields = FieldOutlineUtils.filter(
				classOutline.getDeclaredFields(), getIgnoring());

		if (declaredFields.length > 0) {

			for (final FieldOutline fieldOutline : declaredFields) {
				final JBlock block = body.block();
				final FieldAccessorEx fieldAccessor = getFieldAccessorFactory()
						.createFieldAccessor(fieldOutline, JExpr._this());
				final JVar theValue = block.decl(
						fieldAccessor.getType(),
						"the"
								+ fieldOutline.getPropertyInfo().getName(
										true));
				final JExpression valueIsSet = (fieldAccessor.isAlwaysSet() || fieldAccessor
						.hasSetValue() == null) ? JExpr.TRUE
						: fieldAccessor.hasSetValue();

				fieldAccessor.toRawValue(block, theValue);

				block.invoke(toStringStrategy, "appendField")
						.arg(locator)
						.arg(JExpr._this())
						.arg(JExpr.lit(fieldOutline.getPropertyInfo()
								.getName(false))).arg(buffer).arg(theValue)
						.arg(valueIsSet);
			}
		}
		body._return(buffer);
	}
	return toString$appendFields;
}
 
Example 19
Source File: SimpleHashCodePlugin.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
	protected void generate(ClassOutline classOutline, JDefinedClass theClass) {

		final JCodeModel codeModel = theClass.owner();
		final JMethod object$hashCode = theClass.method(JMod.PUBLIC,
				codeModel.INT, "hashCode");
		object$hashCode.annotate(Override.class);
		{
			final JBlock body = object$hashCode.body();

			final JExpression currentHashCodeExpression = JExpr.lit(1);

			final JVar currentHashCode = body.decl(codeModel.INT,
					"currentHashCode", currentHashCodeExpression);

			final Boolean superClassImplementsHashCode = StrategyClassUtils
					.superClassNotIgnored(classOutline, getIgnoring());

			if (superClassImplementsHashCode != null) {
				body.assign(
						currentHashCode,
						currentHashCode.mul(JExpr.lit(getMultiplier())).plus(
								JExpr._super().invoke("hashCode")));
			}

			final FieldOutline[] declaredFields = FieldOutlineUtils.filter(
					classOutline.getDeclaredFields(), getIgnoring());

			if (declaredFields.length > 0) {

				for (final FieldOutline fieldOutline : declaredFields) {
					final FieldAccessorEx fieldAccessor = getFieldAccessorFactory()
							.createFieldAccessor(fieldOutline, JExpr._this());
					if (fieldAccessor.isConstant()) {
						continue;
					}
					final JBlock block = body.block();
					block.assign(currentHashCode,
							currentHashCode.mul(JExpr.lit(getMultiplier())));

					String propertyName = fieldOutline.getPropertyInfo()
							.getName(true);
					final JVar value = block.decl(fieldAccessor.getType(),
							"the" + propertyName);

					fieldAccessor.toRawValue(block, value);
					final JType exposedType = fieldAccessor.getType();

					final Collection<JType> possibleTypes = FieldUtils
							.getPossibleTypes(fieldOutline, Aspect.EXPOSED);
					final boolean isAlwaysSet = fieldAccessor.isAlwaysSet();
//					final JExpression hasSetValue = exposedType.isPrimitive() ? JExpr.TRUE
//							: value.ne(JExpr._null());
					
					final JExpression hasSetValue = (fieldAccessor.isAlwaysSet() || fieldAccessor
							.hasSetValue() == null) ? JExpr.TRUE
							: fieldAccessor.hasSetValue();					
					getCodeGenerator().generate(
							block,
							exposedType,
							possibleTypes,
							isAlwaysSet,
							new HashCodeArguments(codeModel, currentHashCode,
									getMultiplier(), value, hasSetValue));
				}
			}
			body._return(currentHashCode);
		}
	}
 
Example 20
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 3 votes vote down vote up
static
private void createCopyMethod(JDefinedClass clazz){
	JCodeModel codeModel = clazz.owner();

	JClass reportClazz = codeModel.ref(Report.class);

	JMethod method = clazz.method(JMod.PUBLIC, clazz, "copy");
	method.annotate(Override.class);

	JBlock body = method.body();

	JVar reportVariable = body.decl(reportClazz, "report", JExpr.invoke("getReport"));

	body._return(JExpr._new(clazz).arg(JExpr._super().ref("value")).arg(reportVariable.invoke("copy")).arg(JExpr._null()));
}