Java: creating annotation with default value using Codemodel

I am using the Sun CodeModel code generator for my project. During this time, I ended up creating an annotation class. This class will have an array member that accepts an empty array as default values. See next example:

public class Container {
    public @interface MyAnnotation {
        MyValue[] myValues() default {};
    }
}

      

I used this code to create annotation

JCodeModel codeModel = new JCodeModel();
JDefinedClass myValueClass = codeModel._class(JMod.PUBLIC, "MyValue", ClassType.CLASS);
JDefinedClass containerClass = codeModel._class(JMod.PUBLIC, "Container", ClassType.CLASS);
JDefinedClass annotationClass = containerClass._annotationTypeDeclaration("MyAnnotation");
annotationClass.method(JMod.NONE, myValueClass.array(), "myValues");

      

but I have no idea how to create a default ad. It only generates the following:

public class Container {
    public @interface MyAnnotation {
        MyValue[] myValues();
    }
}

      

+3


source to share


1 answer


JMethod

has a method declareDefaultValue

that allows you to define a default value for the annotation method. The trick after that is to generate an empty array {}

. I haven't been able to figure out how to do this using the existing classes, but you can easily figure it out using JExpressionImpl

:

JCodeModel codeModel = new JCodeModel();
JDefinedClass myValueClass = codeModel._class(JMod.PUBLIC, "MyValue", ClassType.CLASS);
JDefinedClass containerClass = codeModel._class(JMod.PUBLIC, "Container", ClassType.CLASS);
JDefinedClass annotationClass = containerClass._annotationTypeDeclaration("MyAnnotation");
JMethod method = annotationClass.method(JMod.NONE, myValueClass.array(), "myValues");
method.declareDefaultValue(new JExpressionImpl(){
    @Override
    public void generate(JFormatter f) {
        f.p("{}");
    }
});

      



This generates the following:

public @interface MyAnnotation {
    MyValue[] myValues() default {};
}

      

+2


source







All Articles