Java 的注解是用来描述JAVA 源代码的。
J2SE50.的java.lang包中预定义了三个注解:override,deprecated,suppressWarnings.
1. Override注释:仅用于方法,指明注释的方法将覆盖父类中的方法。
2. Deprecated注释:对不应该再使用的方法进行注释,与被声明过时的方法放在同一行。使用被Deprecated注释的方法,编译器会提示过时警告。
3. SuppressWarnings注释:单一注释,可以通过数组提供变量,变量值指明要忽略的特定类型的警告。@SuppressWarnings(value = {'unchecked','fallthrough'})
自定义Annotation:@interface
在讲解自定义Annotation前,首先看一下对注解的注解
Target---这个注解理解起来很简单,即指定注解目标,eg:
@Target(ElementType.METHOD)
@interface MyAnnotation{}
@MyAnnotation// 错误的使用
publicclass Class1
{
@MyAnnotation// 正确的使用
publicvoid myMethod1(){}
}
Target使用一个枚举类型属性,它的值是ElementType.METHOD,表明这个Annotation只能为方法注解。而不能为其它的任何语言元素进行注解。
public enum ElementType {
TYPE, // 指定适用点为 class, interface, enum
FIELD, // 指定适用点为 field
METHOD, // 指定适用点为 method
PARAMETER, // 指定适用点为 method 的 parameter
CONSTRUCTOR, // 指定适用点为 constructor
LOCAL_VARIABLE, // 指定使用点为 局部变量
ANNOTATION_TYPE, //指定适用点为 annotation 类型
PACKAGE // 指定适用点为 package
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
类中有个RetentionPolicy类,也是一个枚举类,具体看代码:
public enum RetentionPolicy {
SOURCE, // 编译器处理完Annotation后不存储在class中
CLASS, // 编译器把Annotation存储在class中,这是默认值
RUNTIME // 编译器把Annotation存储在class中,可以由虚拟机读取,反射需要
}
@Documented:是一个标记注释,表示注释应该出现在类的javadoc中,因为在默认情况下注释时不包括在javadoc中的。
下面开始讲解如何使用自定义注解:
定义注解:
@Retention(RetentionPolicy.RUNTIME) @interface MyAno { String name(); int age(); }
在Father类中注解注解的用途:读取配置,以及设置属性值。@MyAno(name = "tomi",age = 23) public class Father { String str; public void say() { Father f = new Father(); Annotation[] anos = f.getClass().getAnnotations();//取得所有注解 for(Annotation anot : anos) { System.out.println(anot.toString()); if(anot instanceof MyAno) { System.out.println(((MyAno)anot).name()); } } } }
![]()
![]()
![]()
![]()
![]()
![]()