publicenumRetentionPolicy { /** * 保留在源代码,不保留在编译后的字节码文件中 * 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,
/** * 在运行时保留注解,如Spring中的@Autowired,可以通过反射来获取 * 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 }
自定义注解
自定义注解不允许以类的形式实现或继承接口,属性的访问修饰符只能定义成public类型。
创建一个注解,定义可作用于类、方法、字段上。
1 2 3 4 5 6 7 8 9 10 11
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public@interface TestAnnotation { public String name();