Java注解相当于一种标记,在程序中加了注解等于为程序打上一个标记,javac编译器,开发工具或者其他程序可以用反射来了解你的类以及各种元素有没有这样的标记,有则进行相应的处理,标记可以加在 包,类,字段,方法,方法的参数以及局部变量。
注解关键字:
@interface
//简单的注解定义
public @interface MyAnnotation {
}
@Retention 元注解,表示需要在什么级别保存该注释信息(生命周期)。
RententionPolicy.SOURCE 停留在Java源文件,编译就取消。
RetentionPolicy.CLASS 停留在class文件,但会被VM丢弃。
RetentionPolicy.RUNTIME 内存中的字节码,VM将在运行时保留,因此可以通过反射机制读取注解信息。
@Target 元注解,表示该注解用于什么地方。
ElementType.CONSTRUCTOR 构造器声明
ElementType.FIELD 成员变量,对象,属性
ElementType.LOCAL_VARIBLE 局部变量声明
ElementType.METHOD 方法声明
ElementType.PACAGE 包声明
ElementType.PARAM 参数声明
ElementType.TYPE 类、接口或者enum声明
@Documented 将注解包含在JavaDoc中
@Inherited 允许子类继承
@Repeatable 重复注解 JAVA8 新特性
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyAnnotation {
String color();
String value() default "My name is johnson";
int[] array() ;
}
@MyAnnotation(color="red",array={4,5,3})
public class AnnotationInsatance {
public static void main(String[] args){
//验证是否存在注解
if(AnnotationInsatance.class.isAnnotationPresent(MyAnnotation.class)){
//获取注解
MyAnnotation annotation=AnnotationInsatance.class.getAnnotation(MyAnnotation.class);
System.out.println(annotation);
System.out.println(annotation.color());
System.out.println(annotation.array());
System.out.println(annotation.value());
}
}
}
Java8 新特性 重复注解,允许同一类型的注解多次使用在一个类、方法、变量等上面。
java8之前对于重复注解的也有解决办法,但是比较繁琐。
//定义注解
public @interface Authority {
String role();
}
//定义注解 成员变量上面注解的数组
public @interface Authorities {
Authority[] value();
}
public class RepeatAnnotationUseOldVersion {
//变向的重复注解
@Authorities({@Authority(role="Admin"),@Authority(role="Manager")})
public void doSomeThing(){
}
}
下面是java8的解决办法
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
@Repeatable(MyAnnotations.class)
public @interface MyAnnotation {
String color();
String value() default "My name is johnson";
int[] array() ;
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
public @interface MyAnnotations {
MyAnnotation[] value();
}
public class RepeatAnnotationUseNewVersion {
@MyAnnotation(color="red",array={4,5,3})
@MyAnnotation(color="red",array={4,5,3})
public void doSomeThing(){ }
}
要使用好注解,必须熟悉java的反射机制,注解的解析都是通过反射来完成。