下面列出了怎么用 com.sun.codemodel.JDefinedClass 的API类实例代码及写法,或者点击链接到github查看源代码。
private void addSlingAnnotations(JDefinedClass jDefinedClass, JClass adapterClass, String resourceType) {
JAnnotationUse jAUse = jDefinedClass.annotate(codeModel.ref(Model.class));
JAnnotationArrayMember adaptablesArray = jAUse.paramArray("adaptables");
for (String adaptable : adaptables) {
if ("resource".equalsIgnoreCase(adaptable)) {
adaptablesArray.param(codeModel.ref(Resource.class));
}
if ("request".equalsIgnoreCase(adaptable)) {
adaptablesArray.param(codeModel.ref(SlingHttpServletRequest.class));
}
}
if (this.isAllowExporting) {
jAUse.paramArray("adapters").param(adapterClass).param(codeModel.ref(ComponentExporter.class));
} else {
jAUse.param("adapters", adapterClass);
}
if (StringUtils.isNotBlank(resourceType)) {
jAUse.param("resourceType", resourceType);
}
if (this.isAllowExporting) {
jAUse = jDefinedClass.annotate(codeModel.ref(Exporter.class));
jAUse.param("name", codeModel.ref(ExporterConstants.class).staticRef(SLING_MODEL_EXPORTER_NAME));
jAUse.param("extensions", codeModel.ref(ExporterConstants.class).staticRef(SLING_MODEL_EXTENSION));
}
}
private void generateMetaClass(final PluginContext pluginContext, final ClassOutline classOutline, final ErrorHandler errorHandler) throws SAXException {
try {
final JDefinedClass metaClass = classOutline.implClass._class(JMod.PUBLIC | JMod.STATIC, this.metaClassName);
final JMethod visitMethod = generateVisitMethod(classOutline);
for (final FieldOutline fieldOutline : classOutline.getDeclaredFields()) {
if (this.extended) {
generateExtendedMetaField(pluginContext, metaClass, visitMethod, fieldOutline);
} else {
generateNameOnlyMetaField(pluginContext, metaClass, fieldOutline);
}
}
visitMethod.body()._return(JExpr._this());
} catch (final JClassAlreadyExistsException e) {
errorHandler.error(new SAXParseException(getMessage("error.metaClassExists", classOutline.implClass.name(), this.metaClassName), classOutline.target.getLocator()));
}
}
protected static void _importFields(final JDefinedClass theClass, final AtomicInteger index, final SimpleStructureDefinition structure) {
final JClass parentClass = theClass._extends();
if (parentClass != null && parentClass instanceof JDefinedClass) {
_importFields((JDefinedClass)parentClass, index, structure);
}
for (Entry<String, JFieldVar> entry : theClass.fields().entrySet()) {
Class<?> fieldClass = ReflectUtil.loadClass(entry.getValue().type().boxify().erasure().fullName());
String fieldName = entry.getKey();
if (fieldName.startsWith("_")) {
if (!JJavaName.isJavaIdentifier(fieldName.substring(1))) {
fieldName = fieldName.substring(1); //it was prefixed with '_' so we should use the original name.
}
}
structure.setFieldName(index.getAndIncrement(), fieldName, fieldClass);
}
}
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);
}
@Test
public void checkTypeOfDates() throws Exception {
JDefinedClass pojo = getResponsePOJO("/validations", "Validation");
JFieldVar field = getField(pojo, "dateO");
assertThat(field.type().fullName(), is("java.util.Date"));
assertDateFormatAnnotation(field, "yyyy-MM-dd");
field = getField(pojo, "timeO");
assertThat(field.type().fullName(), is("java.util.Date"));
assertDateFormatAnnotation(field, "HH:mm:ss");
field = getField(pojo, "dateTO");
assertThat(field.type().fullName(), is("java.util.Date"));
assertDateFormatAnnotation(field, "yyyy-MM-dd'T'HH:mm:ss");
field = getField(pojo, "dateT");
assertThat(field.type().fullName(), is("java.util.Date"));
assertDateFormatAnnotation(field, "yyyy-MM-dd'T'HH:mm:ssXXX");
field = getField(pojo, "datetimeRFC2616");
assertThat(field.type().fullName(), is("java.util.Date"));
assertDateFormatAnnotation(field, "EEE, dd MMM yyyy HH:mm:ss z");
}
@Override
public JFieldVar apply(ApiResourceMetadata controllerMetadata, JDefinedClass generatableType) {
JFieldVar field = generatableType.field(JMod.PRIVATE, this.fieldClazz, this.fieldName);
// add @Autowired field annoation
if (autowire) {
field.annotate(Autowired.class);
}
// add @Qualifier("qualifierBeanName")
if (qualifierAnnotation && !StringUtils.isEmpty(qualifier)) {
field.annotate(Qualifier.class).param("value", qualifier);
}
// add @Value(value="") annotation to the field
if (valueAnnotation) {
field.annotate(Value.class).param("value", valueAnnotationValue);
}
return field;
}
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAMethodAnnotatedWithId() throws Exception {
// GIVEN
final String simpleClassName = "EntityClass";
final String idPropertyName = "key";
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
jClass.annotate(Entity.class);
jClass.method(JMod.PUBLIC, jCodeModel.VOID, "getKey").annotate(Id.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name());
// WHEN
final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass);
// THEN
assertThat(namesOfIdProperties.size(), equalTo(1));
assertThat(namesOfIdProperties, hasItem(idPropertyName));
}
private JClass getBuilderClass(JClass clazz) {
//Current limitation: this only works for classes from this model / outline, i.e. that are part of this generator run
if (!createBuilder || clazz.isAbstract()) {
return null;
}
String builderClassName = getBuilderClassName(clazz);
if (clazz instanceof JDefinedClass) {
JDefinedClass definedClass = (JDefinedClass) clazz;
for (Iterator<JDefinedClass> i = definedClass.classes(); i.hasNext(); ) {
JDefinedClass innerClass = i.next();
if (builderClassName.equals(innerClass.name())) {
return innerClass;
}
}
}
return null;
}
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;
}
@Override
public final JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel generatableType) {
GenericJavaClassRule generator = new GenericJavaClassRule().setPackageRule(new PackageRule())
.setClassCommentRule(new ClassCommentRule()).addClassAnnotationRule(getControllerAnnotationRule())
.addClassAnnotationRule(new SpringRequestMappingClassAnnotationRule())
.addClassAnnotationRule(new SpringValidatedClassAnnotationRule()).addClassAnnotationRule(new GeneratedClassAnnotationRule())
.setClassRule(new ControllerClassDeclarationRule()).setMethodCommentRule(new MethodCommentRule())
.addMethodAnnotationRule(new SpringRequestMappingMethodAnnotationRule())
.addMethodAnnotationRule(getResponseBodyAnnotationRule())
.setMethodSignatureRule(new ControllerMethodSignatureRule(getReturnTypeRule(false), new SpringMethodParamsRule(
isAddParameterJavadoc(), isAllowArrayParameters(), !Config.isInjectHttpHeadersParameter())))
.setMethodBodyRule(new ImplementMeMethodBodyRule());
return generator.apply(metadata, generatableType);
}
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);
}
@Test
public void applyClassFieldDeclarationRule_shouldCreate_validValueAnnotedField() throws JClassAlreadyExistsException {
ClassFieldDeclarationRule rule = new ClassFieldDeclarationRule("field", String.class, "${sample}");
JPackage jPackage = jCodeModel.rootPackage();
JDefinedClass jClass = jPackage._class(JMod.PUBLIC, "MyClass");
jClass._implements(Serializable.class);
rule.apply(getControllerMetadata(), jClass);
assertFalse(serializeModel().contains("import org.springframework.beans.factory.annotation.Autowired;"));
assertFalse((serializeModel().contains("@Autowired")));
assertThat(serializeModel(), containsString("@Value(\"${sample}\")"));
assertThat(serializeModel(), containsString("private String field;"));
}
public JDefinedClass build(String resourceType) throws JClassAlreadyExistsException {
JDefinedClass jc = this.implPackage._class(this.className)._implements(this.interfaceClass);
addSlingAnnotations(jc, this.interfaceClass, resourceType);
addFieldVars(jc, globalProperties, Constants.PROPERTY_TYPE_GLOBAL);
addFieldVars(jc, sharedProperties, Constants.PROPERTY_TYPE_SHARED);
addFieldVars(jc, privateProperties, Constants.PROPERTY_TYPE_PRIVATE);
addGetters(jc);
addExportedTypeMethod(jc);
return jc;
}
private void generateExtends(JDefinedClass theClass, String name) {
if (name != null) {
final JClass targetClass = theClass.owner().ref(name);
if (theClass._extends() == theClass.owner().ref(Object.class)) {
theClass._extends(targetClass);
}
}
}
MetaInfoOutline(final SelectorGenerator selectorGenerator, final ClassOutline classOutline, final JDefinedClass selectorClass, final JTypeVar rootTypeParam, final JTypeVar parentTypeParam, final JMethod buildChildrenMethod, final JVar productMapVar) {
this.selectorGenerator = selectorGenerator;
this.classOutline = classOutline;
this.selectorClass = selectorClass;
this.rootTypeParam = rootTypeParam;
this.parentTypeParam = parentTypeParam;
this.buildChildrenMethod = buildChildrenMethod;
this.buildChildrenMethod.body().add(productMapVar.invoke("putAll").arg(JExpr._super().invoke(buildChildrenMethod)));
this.productMapVar = productMapVar;
}
private JVar addProperty(JDefinedClass clazz, JFieldVar field) {
JType jType = getJavaType(field);
int builderFieldVisibility = builderInheritance ? JMod.PROTECTED : JMod.PRIVATE;
if (isCollection(field)) {
return clazz.field(builderFieldVisibility, jType, field.name(),
getNewCollectionExpression(field.type().owner(), jType));
} else {
return clazz.field(builderFieldVisibility, jType, field.name());
}
}
private void addNewBuilder(ClassOutline clazz, JDefinedClass builderClass) {
if (builderInheritance || !hasSuperClassWithSameName(clazz)) {
String builderMethodName = generateBuilderMethodName(clazz);
JMethod method = clazz.implClass.method(JMod.PUBLIC | JMod.STATIC, builderClass, builderMethodName);
method.body()._return(JExpr._new(builderClass));
}
}
@Override
public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) {
super.propertyField(field, clazz, propertyName, propertyNode);
if (propertyNode.has("javaOmitEmpty") && propertyNode.get("javaOmitEmpty").asBoolean(false)) {
field.annotate(JsonInclude.class).param(ANNOTATION_VALUE, JsonInclude.Include.NON_EMPTY);
}
}
@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"));
}
/**
* 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);
}
});
}
}
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;
}
private void renderPrivateJaxbConstructor(JDefinedClass classModel, List<FieldModel> fields) {
JMethod method = classModel.constructor(JMod.PRIVATE);
JBlock body = method.body();
for (FieldModel fieldModel : fields) {
body.directStatement("this." + fieldModel.fieldName + " = " + getInitString(fieldModel.fieldType) + ";");
}
method.javadoc().add("Private constructor used only by JAXB.");
}
protected void importStructure(Mapping mapping) {
QName qname = mapping.getElement();
JDefinedClass theClass = (JDefinedClass) mapping.getType().getTypeClass();
SimpleStructureDefinition structure = (SimpleStructureDefinition) this.structures.get(this.namespace + qname.getLocalPart());
Map<String, JFieldVar> fields = theClass.fields();
int index = 0;
for (Entry<String, JFieldVar> entry : fields.entrySet()) {
Class<?> fieldClass = ReflectUtil.loadClass(entry.getValue().type().boxify().fullName());
structure.setFieldName(index, entry.getKey(), fieldClass);
index++;
}
}
/**
* check if a JType is an enum type
*
* @param jType
* @return boolean
*/
private static boolean isEnum(JType jType) {
if (jType instanceof JDefinedClass) { // is enum?
JDefinedClass jDefinedClass = (JDefinedClass) jType;
ClassType classType = jDefinedClass.getClassType();
if (classType == ClassType.ENUM) {
return true;
}
}
return false;
}
CreateBaseVisitorClass(JDefinedClass visitor, Outline outline,
JPackage jPackage,
Function<String, String> visitMethodNamer) {
super(outline, jPackage);
this.visitor = visitor;
this.visitMethodNamer = visitMethodNamer;
}
@Override
public JDocComment apply(ApiResourceMetadata controllerMetadata, JDefinedClass generatableType) {
String comments = "No description";
if (controllerMetadata.getDescription() != null) {
comments = controllerMetadata.getDescription();
}
generatableType.javadoc().append(comments);
generatableType.javadoc().append("\n(Generated with springmvc-raml-parser v." + CodeModelHelper.getVersion() + ")");
return generatableType.javadoc();
}
@Test
public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheClassNameWithSingleTableInheritance() throws Exception {
final String simpleClassNameBase = "EntityClass";
final String simpleClassNameA = "SubEntityClassA";
final String simpleClassNameB = "SubEntityClassB";
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jBaseClass = jp._class(JMod.PUBLIC, simpleClassNameBase);
jBaseClass.annotate(Entity.class);
jBaseClass.annotate(Inheritance.class).param("strategy", InheritanceType.SINGLE_TABLE);
jBaseClass.annotate(DiscriminatorColumn.class).param("name", "TYPE");
final JDefinedClass jSubclassA = jp._class(JMod.PUBLIC, simpleClassNameA)._extends(jBaseClass);
jSubclassA.annotate(Entity.class);
jSubclassA.annotate(DiscriminatorValue.class).param("value", "A");
final JDefinedClass jSubclassB = jp._class(JMod.PUBLIC, simpleClassNameB)._extends(jBaseClass);
jSubclassB.annotate(Entity.class);
jSubclassB.annotate(DiscriminatorValue.class).param("value", "B");
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> baseClass = loadClass(testFolder.getRoot(), jBaseClass.name());
final Class<?> subClassA = loadClass(testFolder.getRoot(), jSubclassA.name());
final Class<?> subClassB = loadClass(testFolder.getRoot(), jSubclassB.name());
final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(simpleClassNameBase),
Arrays.asList(baseClass, subClassA, subClassB));
assertThat(clazz, equalTo(baseClass));
}
private boolean isRelevantPackage(JPackage _package) {
if (_package.propertyFiles().hasNext()) {
return true;
}
Iterator<JDefinedClass> classes = _package.classes();
for (; classes.hasNext();) {
JDefinedClass _class = (JDefinedClass) classes.next();
if (!_class.isHidden()) {
return true;
}
}
return false;
}
private void createReportingVectorClass(JCodeModel codeModel, Class<? extends Vector<?>> vectorClazz, JPrimitiveType type) throws JClassAlreadyExistsException {
JDefinedClass reportingVectorClazz = codeModel._class(JMod.ABSTRACT | JMod.PUBLIC, asReportingClass(vectorClazz), ClassType.CLASS);
reportingVectorClazz._extends(codeModel.ref(vectorClazz));
JFieldVar expressionField = reportingVectorClazz.field(JMod.PRIVATE, String.class, "expression", JExpr.lit(""));
createNewReportMethod(reportingVectorClazz);
createOperationMethods(reportingVectorClazz, vectorClazz, type);
createValueMethods(reportingVectorClazz, type);
createReportMethod(reportingVectorClazz);
createAccessorMethods(reportingVectorClazz, expressionField);
}
private boolean isRelevantPackage(JPackage _package) {
if (_package.propertyFiles().hasNext()) {
return true;
}
Iterator<JDefinedClass> classes = _package.classes();
for (; classes.hasNext();) {
JDefinedClass _class = (JDefinedClass) classes.next();
if (!_class.isHidden()) {
return true;
}
}
return false;
}