简介
Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。
Java 语言中的类、方法、变量、参数和包等都可以被标注。注解的生命周期有三种: 源码,class,运行时.
元注解
元注解的作用就是负责注解其他注解,java 有4个meta-annotation类型,用来提供annotation类型做说明。
1.@Target
2.@Retention
3.@Document
4.@Inhrited
@Target
标记该注解使用的范围
java.lang.annotation.ElementType 定义了使用范围
@Retention
注解的生命周期
java.lang.annotation.RetentionPolicy 定义了注解的生命周期类型
SOURCE 注解将被编译器丢弃
CLASS 注解将在class中使用,但会JVM被丢弃
RUNTIME JVM将在运行期也保存注解,因此可以根据反射获取到注解的信息 ,最常用
@Document
将注解包含着Javadoc中
@Inhrited
允许子类继承父类的注解
注解中的参数类型
注解中的参数只支持如下类型:
所有的基本类型:byte、short、char、int、long、float、double
String类型
Class类型
enum类型
Annotation类型
以上类型的数组
如果定义其他类型的参数编译器会报错。
示例
示例代码github.
创建一个注解,抽象类,demo类
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface AnnotationDemo {
String value() default "default";
}
@AnnotationDemo("注解继承来自父类的AbstractClassDemo")
public abstract class AbstractClassDemo {
}
//@AnnotationDemo
public class ClassDemo extends AbstractClassDemo{
@AnnotationDemo(value = "属性")
private String name;
@AnnotationDemo
private String def;
@AnnotationDemo(value = "一般方法")
public String setName(String name){
return name;
}
@AnnotationDemo(value = "构造器")
public ClassDemo(){
}
}
测试类
@Test
public void testAnnotation() throws Exception{
Class clazz = ClassDemo.class;
Object obj = clazz.newInstance();
//获取属性
Field[] fields = clazz.getDeclaredFields();
//获取方法
Method[] methods = clazz.getDeclaredMethods();
for (Field field : fields) {
//是否有该注解
if (field.isAnnotationPresent(AnnotationDemo.class)) {
//获取指定注解
AnnotationDemo annotation = field.getAnnotation(AnnotationDemo.class);
//获取注解值
System.out.print("属性注解:" + annotation.value()+ "\n");
field.setAccessible(true);
field.set(obj,annotation.value());
}
}
for (Method method : methods) {
if (method.isAnnotationPresent(AnnotationDemo.class)) {
AnnotationDemo annotation = method.getAnnotation(AnnotationDemo.class);
System.out.print("方法注解值:" + annotation.value() + "\n");
}
}
//获取类上所有注解
clazz.getAnnotations();
if (clazz.isAnnotationPresent(AnnotationDemo.class)){
AnnotationDemo annotation = (AnnotationDemo) clazz.getAnnotation(AnnotationDemo.class);
System.out.println("类上注解: " + annotation.value());
}
Constructor constructor = clazz.getConstructor();
//获取构造起上所有注解
constructor.getAnnotations();
if (constructor.isAnnotationPresent(AnnotationDemo.class)) {
AnnotationDemo annotationDemo = (AnnotationDemo)constructor.getAnnotation(AnnotationDemo.class);
System.out.println("构造器注解值: " + annotationDemo.value());
}
}