Java 注解 Annotation
1.理解Annotation
(1)从jdk5.0开始,Java增加了对元数据(MetaData)的支持,也就是Annotation
(2)Annotation其实就是代码里的特殊标记,这些标记可以在编译,类加载,运行时被读取,
并执行相应的处理。通过使用Annotation,程序员可以在不改变原有逻辑的情况下,在源文件中嵌入一些补充信息。
(3)在JavaSE中,注解的使用目的比较简单,例如标记过时的功能,忽略警告等。在JavaEE/Android中注解占据了
更重要的角色,例如用来配置应用程序的任何切面,代替JavaEE旧版中所遗留的繁冗代码和XML配置。
2.Annotation使用示例
示例1:生成文档相关的注解
示例2:在编译时进行格式检查(JDK内置的三个基本注解)
@Override:限定重写父类,该注解只能用于方法
@Deprecated:用于表示所修饰的元素(类,方法等)已过时。通常是因为所修饰的结果危险或存在更好的替代
@SuppressWarnings:抑制编译器警告
示例3:跟踪代码依赖性,实现替代配置文件功能
3.如何自定义注解
(1)参考SuppressWarning的定义
(2)内部定义成员,通常使用value表示
(3)可以指定成员的默认值,使用default定义
(4)如果自定义注解没有成员,表明是一个标识作用。
如果注解有成员,在使用注解时,需要指明成员的值。
自定义注解必须配上注解的信息处理流程(使用反射)才有意义。
自定义注解通常会指明两个元注解:Retention 和Target
4.元注解
元注解:对现有注解进行解释说明的注解
Retention:指定所修饰注解的生命周期(SOURCE,CLASS(默认行为),RUNTIME),只有声明为RUNTIME生命周期的注解,才能通过反射获取。
Target:指定被修饰的Annotation能用于修饰哪些程序元素,比如SuppressWarnings的 @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
******出现的频率较低***********
Documented:表示所修饰的注解在被Javadoc解析时,会被保留下来,如 @Deprecated可以在API文档显示
Inherit:被它修饰的Annotation将具有继承性。
5.通过反射获取注解信息----到反射内容时系统学习。
6.jdk8 中注解的新特性。
(1)可重复注解:声明元注解@Repeatable,成员值为修饰注解类本身。
(2)类型注解:
ElementType.TYPE_PARAMETER 表示该注解能写在类型变量的声明语句中(如泛型声明)
ElementType.TYPE_USE 表示该注解能写在使用类型的任何语句中。
@Retention(RetentionPolicy.RUNTIME)//指明注解的生命周期是runtime @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) //修饰类型范围 public @interface MyAnnotation { String value() default "hi";//设定注解默认值 }
@SuppressWarnings
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings { /** * The set of warnings that are to be suppressed by the compiler in the * annotated element. Duplicate names are permitted. The second and * successive occurrences of a name are ignored. The presence of * unrecognized warning names is <i>not</i> an error: Compilers must * ignore any warning names they do not recognize. They are, however, * free to emit a warning if an annotation contains an unrecognized * warning name. * * <p> The string {@code "unchecked"} is used to suppress * unchecked warnings. Compiler vendors should document the * additional warning names they support in conjunction with this * annotation type. They are encouraged to cooperate to ensure * that the same names work across multiple compilers. * @return the set of warnings to be suppressed */ String[] value(); }

浙公网安备 33010602011771号