- 注解的RetentionPolicy分为:
```java
/**
- Annotations are to be discarded by the compiler. */ SOURCE,
/**
- Annotations are to be recorded in the class file by the compiler
- but need not be retained by the VM at run time. This is the default
- behavior. */ CLASS,
/**
- Annotations are to be recorded in the class file by the compiler and
- retained by the VM at run time, so they may be read reflectively. *
- @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
Lombok @Data注解就是SOURCE级别,其中有个不常见的用法:静态构造器。
public @Data(staticConstructor = “of”) class Point { final int x, y; }
Point.of(x,y) 即可new对象 ```
- java文件到class文件再到被jvm加载的过程如下:
其中注解抽象语法树就会解析注解并处理逻辑。
所以,如果想要在编译期间处理注解逻辑,需要继承AbstractProcessor并实现process方法。 一般来说,只要自定义为Source和Class级别的注解就需要继承实现。否则等到加载到JVM时, 注解就被抹掉了。
- 我们在开发时大多数用的Runtime级别,根据运行时环境做一些处理,需要配合反射一起用。 Source注解例子:www.baeldung.com