Search code examples
javaannotationssun-codemodeljcodemodel

How to remove an annotation on a JDefinedClass


I am writing an custom annotator in jsonschema2pojo in order to tweak how this code generator annotates generated class with Jackson annotations.

To simplify the usecase, I have a JClass at hand that is already annotation with

JsonInclude( JsonInclude.Include.NON_NULL )

and I want to replace it with:

JsonInclude( JsonInclude.Include.NON_EMPTY )

I am using com.sun.codemodel:codemodel:2.6

If I attempt to add the annotation without removing the original one

JDefinedClass clazz = ...; // the class we want to annotate
clazz.annotate(JsonInclude.class).param( "value", JsonInclude.Include.NON_EMPTY );

Then I get a compile error saying that I cannot have mode than one @JsonInclude.

So I tried to remove the annotation prior to adding it

JCodeModel codeModel = new JCodeModel();
JClass jsonInclude = codeModel.ref(JsonInclude.class);
clazz.annotations().remove( jsonInclude );

but the collection of annotations is unmodifiable...

Is there a way to remove a specific annotation from a JDefinedClass ?


Solution

  • Looking over the JCodeModel source, you're correct, there isn't a way to remove an annotation without breaking the class through reflection (accessing private member variables):

    public Collection<JAnnotationUse> annotations() {
        if(this.annotations == null) {
            this.annotations = new ArrayList();
        }
    
        return Collections.unmodifiableCollection(this.annotations);
    }
    

    I'd recommend trying to determine which annotation is appropriate (NON_NULL or NON_EMPTY) at a higher level in your application, somewhere before you need to define the JDefinedClass. For code generators I've written I typically have a model prepared before I go to the code generation phase which helps guard against making decisions about what to generate after it has been specified.