下面列出了怎么用 com.sun.codemodel.JMethod 的API类实例代码及写法,或者点击链接到github查看源代码。
private void generateBuilderMethodJavadoc(
final JMethod method,
final String methodPrefix,
final String propertyName,
final String schemaAnnotation) {
final String endMethodClassName = method.type().erasure().fullName();
JavadocUtils.appendJavadocCommentParagraphs(
method.javadoc(),
settings.isGeneratingJavadocFromAnnotations() ? schemaAnnotation : null,
MessageFormat.format(
this.resources.getString("comment." + methodPrefix + "BuilderMethod"),
propertyName,
endMethodClassName))
.addReturn()
.append(JavadocUtils.hardWrapTextForJavadoc(MessageFormat.format(
this.resources.getString("comment." + methodPrefix + "BuilderMethod.return"),
propertyName,
endMethodClassName)));
}
private FieldOutline generateProperty(final DefinedInterfaceOutline groupInterface, final FieldOutline implementedField) {
if (implementedField != null) {
final JMethod implementedGetter = PluginContext.findGetter(implementedField);
if (implementedGetter != null) {
if(this.overrideCollectionClass != null && implementedField.getPropertyInfo().isCollection()) {
groupInterface.getImplClass().method(JMod.NONE, this.overrideCollectionClass.narrow(((JClass)implementedGetter.type()).getTypeParameters().get(0)), implementedGetter.name());
} else {
groupInterface.getImplClass().method(JMod.NONE, implementedGetter.type(), implementedGetter.name());
}
if (!this.immutable) {
final JMethod implementedSetter = PluginContext.findSetter(implementedField);
if (implementedSetter != null) {
final JMethod newSetter = groupInterface.getImplClass().method(JMod.NONE, implementedSetter.type(),
implementedSetter.name());
newSetter.param(implementedSetter.listParamTypes()[0], implementedSetter.listParams()[0].name());
if (this.throwsPropertyVetoException) {
newSetter._throws(PropertyVetoException.class);
}
}
}
groupInterface.addField(implementedField);
}
}
return implementedField;
}
private JMethod createMethod(final Schema schema, boolean read) {
if (!Schema.Type.RECORD.equals(schema.getType())) {
throw new FastDeserializerGeneratorException("Methods are defined only for records, not for " + schema.getType());
}
if (methodAlreadyDefined(schema, read)) {
throw new FastDeserializerGeneratorException("Method already exists for: " + schema.getFullName());
}
JClass schemaClass = schemaAssistant.classFromSchema(schema);
JMethod method = generatedClass.method(JMod.PUBLIC, read ? schemaClass : codeModel.VOID,
getUniqueName("deserialize" + schema.getName()));
method._throws(IOException.class);
method.param(Object.class, VAR_NAME_FOR_REUSE);
method.param(Decoder.class, DECODER);
(read ? deserializeMethodMap : skipMethodMap).put(schema.getFullName(), method);
return method;
}
private JMethod generateGetterMethod(JFieldVar field, String fieldName, JExpression defaultValue) {
String javaName = NamingHelper.convertToClassName(fieldName);
// Add get method
JMethod getter = this.pojo.method(JMod.PUBLIC, field.type(), "get" + javaName);
if (defaultValue != null) {
JBlock body = getter.body();
body._if(field.eq(JExpr._null()))._then()._return(defaultValue);
}
getter.body()._return(field);
getter.javadoc().add("Returns the " + fieldName + ".");
getter.javadoc().addReturn().add(field.name());
return getter;
}
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;
}
void processToStruct(JFieldVar schemaField, JCodeModel codeModel, ClassOutline classOutline) {
final Map<String, JFieldVar> fields = classOutline.implClass.fields();
final JClass structClass = codeModel.ref(Struct.class);
final JMethod method = classOutline.implClass.method(JMod.PUBLIC, structClass, "toStruct");
final JBlock methodBody = method.body();
final JVar structVar = methodBody.decl(structClass, "struct", JExpr._new(structClass).arg(schemaField));
for (final Map.Entry<String, JFieldVar> field : fields.entrySet()) {
log.trace("processSchema() - processing name = '{}' type = '{}'", field.getKey(), field.getValue().type().name());
if (schemaField.name().equals(field.getKey())) {
log.trace("processSchema() - skipping '{}' cause we added it.", field.getKey());
continue;
}
methodBody.invoke(structVar, "put")
.arg(field.getKey())
.arg(JExpr.ref(JExpr._this(), field.getKey()));
}
methodBody._return(structVar);
}
private void replaceCollectionGetter(JDefinedClass ownerClass, JFieldVar field, final JMethod getter) {
// remove the old getter
ownerClass.methods().remove(getter);
// and create a new one
JMethod newGetter = ownerClass.method(getter.mods().getValue(), getter.type(), getter.name());
JBlock block = newGetter.body();
JVar ret = block.decl(getJavaType(field), "ret");
JCodeModel codeModel = field.type().owner();
JVar param = generateMethodParameter(getter, field);
JConditional conditional = block._if(param.eq(JExpr._null()));
conditional._then().assign(ret, getEmptyCollectionExpression(codeModel, param));
conditional._else().assign(ret, getUnmodifiableWrappedExpression(codeModel, param));
block._return(ret);
getter.javadoc().append("Returns unmodifiable collection.");
}
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;
}
@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 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);
}
/**
* @throws IllegalStateException
* if a packageRule or classRule is missing or if the
* ApiControllerMetadata requires a missing methodSignatureRule.
*/
@Override
public JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel codeModel) {
if (packageRule == null || classRule == null) {
throw new IllegalStateException("A packageRule and classRule are mandatory.");
}
if (!metadata.getApiCalls().isEmpty() && methodSignatureRule == null) {
throw new IllegalStateException("Since there are API Calls in the metadata at least a methodSignatureRule is mandatory");
}
JPackage jPackage = packageRule.apply(metadata, codeModel);
JDefinedClass jClass = classRule.apply(metadata, jPackage);
implementsExtendsRule.ifPresent(rule -> rule.apply(metadata, jClass));
classCommentRule.ifPresent(rule -> rule.apply(metadata, jClass));
classAnnotationRules.forEach(rule -> rule.apply(metadata, jClass));
fieldDeclerationRules.forEach(rule -> rule.apply(metadata, jClass));
metadata.getApiCalls().forEach(apiMappingMetadata -> {
JMethod jMethod = methodSignatureRule.apply(apiMappingMetadata, jClass);
methodCommentRule.ifPresent(rule -> rule.apply(apiMappingMetadata, jMethod));
methodAnnotationRules.forEach(rule -> rule.apply(apiMappingMetadata, jMethod));
methodBodyRule.ifPresent(rule -> rule.apply(apiMappingMetadata, CodeModelHelper.ext(jMethod, jClass.owner())));
});
return jClass;
}
private void processAttributeWildcard(ClassOutline classOutline) {
logger.debug("The class ["
+ OutlineUtils.getClassName(classOutline)
+ "] declares an attribute wildcard which will be made transient.");
String FIELD_NAME = "otherAttributes";
String METHOD_SEED = classOutline.parent().getModel()
.getNameConverter().toClassName(FIELD_NAME);
final JMethod getOtherAttributesMethod = classOutline.ref.getMethod(
"get" + METHOD_SEED, new JType[0]);
if (getOtherAttributesMethod == null) {
logger.error("Could not find the attribute wildcard method in the class ["
+ OutlineUtils.getClassName(classOutline) + "].");
} else {
getOtherAttributesMethod.annotate(Transient.class);
}
}
private boolean variablesOverlap(JMethod method, JMethod interfaceMethod) {
boolean overlap = true;
for (JVar implParam : method.params()) {
boolean found = false;
for (JVar newParam : interfaceMethod.params()) {
if (newParam.type().fullName().equalsIgnoreCase(implParam.type().fullName())) {
found = true;
break;
}
}
if (!found) {
overlap = false;
break;
}
}
return overlap;
}
public static JMethod getMethod(JDefinedClass theClass, String name,
JType[] arguments) {
final JMethod method = theClass.getMethod(name, arguments);
if (method != null) {
return method;
} else {
final JClass draftSuperClass = theClass._extends();
if (draftSuperClass == null
|| !(draftSuperClass instanceof JDefinedClass)) {
return null;
} else {
final JDefinedClass superClass = (JDefinedClass) draftSuperClass;
return getMethod(superClass, name, arguments);
}
}
}
protected JMethod generateMergeFrom$mergeFrom0(
final ClassOutline classOutline, final JDefinedClass theClass) {
JCodeModel codeModel = theClass.owner();
final JMethod mergeFrom$mergeFrom = theClass.method(JMod.PUBLIC,
codeModel.VOID, "mergeFrom");
mergeFrom$mergeFrom.annotate(Override.class);
{
final JVar left = mergeFrom$mergeFrom.param(Object.class, "left");
final JVar right = mergeFrom$mergeFrom.param(Object.class, "right");
final JBlock body = mergeFrom$mergeFrom.body();
final JVar mergeStrategy = body.decl(JMod.FINAL,
codeModel.ref(MergeStrategy2.class), "strategy",
createMergeStrategy(codeModel));
body.invoke("mergeFrom").arg(JExpr._null()).arg(JExpr._null())
.arg(left).arg(right).arg(mergeStrategy);
}
return mergeFrom$mergeFrom;
}
JMethod generateBuildMethod(final JMethod initMethod) {
final JMethod buildMethod = this.builderClass.raw.method(JMod.PUBLIC, this.definedClass, this.settings.getBuildMethodName());
if (!(this.builderClass.type._extends() == null || this.builderClass.type._extends().name().equals("java.lang.Object"))) {
buildMethod.annotate(Override.class);
}
if (this.implement) {
final JExpression buildExpression = JExpr._this().invoke(initMethod).arg(JExpr._new(this.definedClass));
if (this.settings.isCopyAlways()) {
buildMethod.body()._return(buildExpression);
} else if (this.definedClass.isAbstract()) {
buildMethod.body()._return(JExpr.cast(this.definedClass, this.storedValueField));
} else {
final JConditional jConditional = buildMethod.body()._if(this.storedValueField.eq(JExpr._null()));
jConditional._then()._return(buildExpression);
jConditional._else()._return(JExpr.cast(this.definedClass, this.storedValueField));
}
}
return buildMethod;
}
private void addConstructor7Args() {
/* constructor, init the httpClient - allow to pass keep alive option */
JMethod constructor = constructor();
JVar host = constructor.param(String.class, "host");
JVar port = constructor.param(int.class, "port");
JVar tenantIdVar = constructor.param(String.class, TENANT_ID);
JVar tokenVar = constructor.param(String.class, TOKEN);
JVar keepAlive = constructor.param(boolean.class, KEEP_ALIVE);
JVar connTimeout = constructor.param(int.class, "connTO");
JVar idleTimeout = constructor.param(int.class, "idleTO");
JBlock conBody = constructor.body();
conBody.invoke("this").arg(okapiUrl(host, port)).arg(tenantIdVar).arg(tokenVar).arg(keepAlive)
.arg(connTimeout).arg(idleTimeout);
deprecate(constructor);
}
protected JMethod generateObject$equals(final ClassOutline classOutline,
final JDefinedClass theClass) {
final JCodeModel codeModel = theClass.owner();
final JMethod objectEquals = theClass.method(JMod.PUBLIC,
codeModel.BOOLEAN, "equals");
objectEquals.annotate(Override.class);
{
final JVar object = objectEquals.param(Object.class, "object");
final JBlock body = objectEquals.body();
final JVar equalsStrategy = body.decl(JMod.FINAL,
codeModel.ref(EqualsStrategy2.class), "strategy",
createEqualsStrategy(codeModel));
body._return(JExpr.invoke("equals").arg(JExpr._null())
.arg(JExpr._null()).arg(object).arg(equalsStrategy));
}
return objectEquals;
}
static
private void moveAfter(JDefinedClass beanClazz, JMethod method, JMethod referenceMethod){
List<JMethod> methods = (List<JMethod>)beanClazz.methods();
int index = methods.indexOf(referenceMethod);
if(index < 0){
throw new RuntimeException();
}
methods.remove(method);
methods.add(index + 1, method);
}
/**
* method just adds getters based on the properties of generationConfig
*
* @param jc the interface class
* @param properties the list of properties
*/
private void addGettersWithoutFields(JDefinedClass jc, List<Property> properties) {
if (properties != null && !properties.isEmpty()) {
properties.stream()
.filter(Objects::nonNull)
.forEach(property -> {
JMethod method = jc.method(NONE, getGetterMethodReturnType(property), Constants.STRING_GET + property.getFieldGetterName());
addJavadocToMethod(method, property);
if (this.isAllowExporting) {
if (!property.isShouldExporterExpose()) {
method.annotate(codeModel.ref(JsonIgnore.class));
}
if (StringUtils.isNotBlank(property.getJsonProperty())) {
method.annotate(codeModel.ref(JsonProperty.class))
.param("value", property.getJsonProperty());
}
}
if (property.getType().equalsIgnoreCase("multifield")
&& property.getItems().size() > 1) {
buildMultifieldInterface(property);
}
});
}
}
@Test
public void applyRule_shouldCreate_validMethodComment() throws JClassAlreadyExistsException {
JDefinedClass jClass = jCodeModel.rootPackage()._class("TestController");
JMethod jMethod = jClass.method(JMod.PUBLIC, ResponseEntity.class, "getBaseById");
JDocComment jDocComment = rule.apply(getEndpointMetadata(2), jMethod);
assertNotNull(jDocComment);
assertThat(serializeModel(), containsString("* Get base entity by ID"));
}
protected void processClassOutline(ClassOutline classOutline) {
final JDefinedClass theClass = classOutline.implClass;
ClassUtils._implements(theClass, theClass.owner().ref(HashCode2.class));
@SuppressWarnings("unused")
final JMethod hashCode$hashCode = generateHashCode$hashCode(
classOutline, theClass);
@SuppressWarnings("unused")
final JMethod object$hashCode = generateObject$hashCode(classOutline,
theClass);
}
private void generateWithMethodJavadoc(final JMethod method, final JVar param, final String schemaAnnotation) {
final String propertyName = param.name();
JavadocUtils.appendJavadocCommentParagraphs(
method.javadoc(),
settings.isGeneratingJavadocFromAnnotations() ? schemaAnnotation : null,
MessageFormat.format(this.resources.getString("comment.withMethod"), propertyName))
.addParam(param)
.append(JavadocUtils.hardWrapTextForJavadoc(MessageFormat.format(
this.resources.getString("comment.withMethod.param"),
propertyName)));
}
private void renderGetters(JDefinedClass classModel, List<FieldModel> fields) {
for (FieldModel fieldModel : fields) {
JMethod getterMethod = classModel.method(JMod.PUBLIC, fieldModel.fieldType, Util.generateGetterName(fieldModel.fieldName, isBoolean(fieldModel.fieldType)));
JBlock methodBody = getterMethod.body();
methodBody.directStatement("return this." + fieldModel.fieldName + ";");
getterMethod.annotate(Override.class);
}
}
@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 JMethod innerMethod(CompleteType type) {
JMethod method = clazz.method(JMod.PRIVATE, type.getHolderClass(), "inner_method_" + innerMethodCount++);
String methodName = getCurrentMapping().getMethodName(BlockType.EVAL);
CodeGeneratorMethod cgm = sig.get(sig.get(methodName));
for (CodeGeneratorArgument arg : cgm) {
method.param(arg.getType(), arg.getName());
}
nestEvalBlock(method.body());
evaluationVisitor.previousExpressions.clear();
return method;
}
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;
}
public static JMethod getMethod(final JDefinedClass theClass,
final String name) {
for (JMethod method : theClass.methods()) {
if (method.name().equals(name))
return method;
}
return null;
}
BuilderGenerator(final PluginContext pluginContext, final Map<String, BuilderOutline> builderOutlines, final BuilderOutline builderOutline, final BuilderGeneratorSettings settings) {
this.pluginContext = pluginContext;
this.settings = settings;
this.builderOutlines = builderOutlines;
this.typeOutline = (DefinedTypeOutline)builderOutline.getClassOutline();
this.definedClass = this.typeOutline.getImplClass();
this.builderClass = new GenerifiedClass(builderOutline.getDefinedBuilderClass(), BuilderGenerator.PARENT_BUILDER_TYPE_PARAMETER_NAME);
this.resources = ResourceBundle.getBundle(BuilderGenerator.class.getName());
this.implement = !this.builderClass.raw.isInterface();
if (builderOutline.getClassOutline().getSuperClass() == null) {
final JMethod endMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.typeParam, this.settings.getEndMethodName());
if (this.implement) {
this.parentBuilderField = this.builderClass.raw.field(JMod.PROTECTED | JMod.FINAL, this.builderClass.typeParam, BuilderGenerator.PARENT_BUILDER_PARAM_NAME);
endMethod.body()._return(JExpr._this().ref(this.parentBuilderField));
this.storedValueField = this.settings.isCopyAlways() ? null : this.builderClass.raw.field(JMod.PROTECTED | JMod.FINAL, this.definedClass, BuilderGenerator.STORED_VALUE_PARAM_NAME);
} else {
this.parentBuilderField = null;
this.storedValueField = null;
}
} else {
this.parentBuilderField = null;
this.storedValueField = this.implement ? JExpr.ref(BuilderGenerator.STORED_VALUE_PARAM_NAME) : null;
}
if (this.implement) {
generateCopyConstructor(false);
if (this.settings.isGeneratingPartialCopy()) {
generateCopyConstructor(true);
}
}
}
@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 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 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());
try {
// WHEN
new JpaUnitRule(cut);
fail("IllegalArgumentException expected");
} catch (final IllegalArgumentException e) {
// THEN
assertThat(e.getMessage(), containsString("Only single field is allowed"));
}
}