简体   繁体   中英

Pattern for processing custom Java annotations

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?

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 ).

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?

如果你想在运行时处理你的注解,你需要从 classLoader 的信息中扫描类,这个答案提供了更多关于它的信息: How do I read all classes from a Java package in the classpath?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM