1

I have read a lot of tutorials about Java annotations lately and I like the idea of creating a custom one. Most articles cover the very basic idea and fairly simple implementations. I'm missing a proper pattern to process my annotation, though.

Lets say I have a custom annotation @Foobar to initialize fields. I need to pass all classes that use this annotation to my processor, let's call it FoobarProcessor:

public class AnnotatedClass {
  @Foobar
  private String test = "";

  static {
    FoobarProcessor.process(AnnotatedClass.class);
  }
}

Is there any approach to overcome this drawback? Is there any single point that all classes pass, where I can easily apply my annotation processor?

kapex
  • 28,903
  • 6
  • 107
  • 121
user1438038
  • 5,821
  • 6
  • 60
  • 94

3 Answers3

2

A common pattern to process annotations or any language elements is the visitor pattern.

Java even includes a standard API for to this: SimpleElementVisitor7

If you need an example implementation of a processor using the pattern, take a look at the code of the PrintingProcessor. The processor traverses all kind of elements it find and prints some information. It's used for javac's non-standard Xprint option (you can try it in your command line: javac -Xprint java.lang.Object).

kapex
  • 28,903
  • 6
  • 107
  • 121
0

You need to register the processor in a META-INF file. This answer should give you more info:

What is the default annotation processors discovery process?

Community
  • 1
  • 1
Guy Bouallet
  • 2,099
  • 11
  • 16
0

If you want to process your annotation at Runtime, you need to scan the classes from information of the classLoader, this answer give more information about it: How do I read all classes from a Java package in the classpath?

Community
  • 1
  • 1
pdem
  • 3,880
  • 1
  • 24
  • 38