3

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 ?

Samuel Kerrien
  • 6,965
  • 2
  • 29
  • 32
  • Isn't this somehow related to this question? http://stackoverflow.com/questions/6467511/remove-annotations-in-subclass – Genti Saliu Jan 19 '16 at 11:06
  • @Genti: not really, while my question relates to removing annotations from a class, it is specific to the use of the code generation library "com.sun.codemodel". The question you referenced relates to removing annotations on an arbitrary object instance. – Samuel Kerrien Jan 19 '16 at 12:39

1 Answers1

2

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.

John Ericksen
  • 10,995
  • 4
  • 45
  • 75
  • 1
    Thanks john, it's a sensible approach. however in my case I am I am getting an already build JDefinedClass from a third party code generator (jsonschema2pojo). Thanks ! – Samuel Kerrien Jan 20 '16 at 15:42
  • 1
    That's too bad... Could you copy the JDefinedClass into a new one, filtering as you go? – John Ericksen Jan 20 '16 at 19:51
  • Found a work around that does not involve working around the limitation of the codemodel API. In the end I have been able to annotate field in my class instead the class to get the behaviour I was after. Thanks for taking the time to help John ! – Samuel Kerrien Jan 21 '16 at 08:41