元标记有@Retention、@Documented、@Target、@Inherited、@Repeatable 5这5种。
@Retention
Retention的英语意思是保存期间的意思。 说明将@Retention应用于评论时,该评论的生存时间。
这些值包括:
RetentionPolicy.SOURCE注释仅在源代码阶段保留,并在编译器编译时被丢弃和忽略。
RetentionPolicy.CLASS注释仅在编译时保留,而不加载到JVM中。
RetentionPolicy.RUNTIME注释在程序运行时保留并加载到JVM中,以便在程序运行时检索。
如果@Retention不存在,则Annotation默认为CLASS。 通常,我们定制的所有Annotation都是RUNTIME,因此请务必添加@ retention (retention policy.runtime )元注释。
@ retention (retention policy.runtime ) public@interfacereport ) inttype ) ) default0; 字符串级别(default ' info ); String value () default ' ); } @Documented
drdzjy,这个元评论一定与文档有关。 可以将注释中的元素包含在Javadoc中。
@Target
Target是目标的意思,@Target指定评论的运用场所。
这样,某个评论发表@Target评论时,可以理解为该评论限定了运用的场景。
例如,要将注释@Report定义为可在方法中使用,必须添加@target(elementtype.method )。
@target(elementtype.method ) public@interfacereport ) inttype ) ) default0; 字符串级别(default ' info ); String value () default ' ); }注释定义@Report可用于方法或字段中,并且可以将@Target注释参数更改为数组{ ElementType.METHOD,ElementType.FIELD }。
@Target(elementtype.method,ElementType.FIELD} ) ) public@interfacereport )…}实际上@target定义的value是ElementType[]
@Inherited
Inherited表示继承,但并不意味着注释本身可以继承,如果超类对@Inherited注释的注释进行注释,则表示该子类未应用于任何注释如果父类具有注释,并且子类没有应用注释,则子类将继承父类的注释
@repeatable(reports.class ) target ) elementtype.type ) public@interfacereport ) inttype ) default0; 字符串级别(default ' info ); String value () default ' ); }@target(elementtype.type ) public@interfacereports ) rep
ort[] value();}经过@Repeatable修饰后,在某个类型声明处,就可以添加多个@Report注解:
@Report(type=1, level="debug")@Report(type=2, level="warning")public class Hello {}@Repeatable
Repeatable 自然是可重复的意思。通常是注解的值可以同时取多个
@Repeatable(Reports.class)@Target(ElementType.TYPE)public @interface Report { int type() default 0; String level() default "info"; String value() default "";}@Target(ElementType.TYPE)public @interface Reports { Report[] value();}经过@Repeatable修饰后,在某个类型声明处,就可以添加多个@Report注解:
@Report(type=1, level="debug")@Report(type=2, level="warning")public class Hello {}
Java预置的注解
@Deprecated
这个元素是用来标记过时的元素,想必大家在日常开发中经常碰到。编译器在编译阶段遇到这个注解时会发出提醒警告,告诉开发者正在调用一个过时的元素比如过时的方法、过时的类、过时的成员变量。
@Override
这个大家应该很熟悉了,提示子类要复写父类中被 @Override 修饰的方法
@SuppressWarnings
阻止警告的意思。之前说过调用被 @Deprecated 注解的方法后,编译器会警告提醒,而有时候开发者会忽略这种警告,他们可以在调用的地方通过 @SuppressWarnings 达到目的。
@SafeVarargs
参数安全类型注解。它的目的是提醒开发者不要用参数做一些不安全的操作,它的存在会阻止编译器产生 unchecked 这样的警告。它是在 Java 1.7 的版本中加入的。
@FunctionalInterface
函数式接口注解,这个是 Java 1.8 版本引入的新特性。函数式编程很火,所以 Java 8 也及时添加了这个特性。函数式接口 (Functional Interface) 就是一个具有一个方法的普通接口。
注解通过反射获取。首先可以通过 Class 对象的 isAnnotationPresent() 方法判断它是否应用了某个注解
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {}然后通过 getAnnotation() 方法来获取 Annotation 对象。
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {}或者是 getAnnotations() 方法。
public Annotation[] getAnnotations() {}