Search code examples
javaannotation-processing

Java annotation processing - how to handle already processed code?


If I have a class

@GenerateInterface
public class _FooImpl {}

I want to generate an interface

public interface Foo {}

that basically contains all the methods of _FooImpl (i.e. getters and setters).

Also if I have inheritance, like

@GenerateInterface
public class _ParentImpl {}

@GenerateInterface
public class _ChildImpl extends _ParentImpl {}

this should result in interface inheritance as well

public interface Parent {}

public interface Child extends Parent {}

I have a rough idea how to do that. But what if _ParentImpl is part of a library? That library also has to contain Parent.

In the annotation processor, how do I handle this? I can't generate the Parent interface again because then I'd have the same interface twice. Can I somehow detect that it already exists but distinguish it from files that do also already exist but are not part of the library and can thus be overriden?

I actually only need this for one class/interface that is extended by anything else. Thus I could remove @GenerateInterface from _ParentImpl and hardcode the inheritance of the Parent interface. This would be my last resort though. Edit: Or instead of removing the interface altogether, I could set @Retention(RetentionPolicy.SOURCE), right?


Solution

  • Already compiled classes are not processed again.

    I created a complete test set-up and explored the issue myself. Turns out, only files that actually have to be compiled are run through annotation processing. This means I can safely include _ParentImpl and Parent in the library. _ParentImpl can keep the annotation, it is then possible to use @Retention(RetentionPolicy.CLASS) in connection with @Inherited to apply the annotation to subclasses in a very convenient manner.