一. 概述
注解:就是Java代码里的特殊标记,比如@Override、@Test等,作用就是让其他程序根据注解信息来决定怎么执行该程序。
二. 自定义注解
格式:public @interface 注解名称{
public 属性名称 属性名() default 默认值;
}
特殊属性名:value:如果注解中只有一个value属性,使用注解时,value名称可以不写
public @interface MyAnnotation1 {String aaa();String bbb() default "bbb";String ccc();
}public @interface MyAnnotation2 {String value();
}@MyAnnotation1(aaa="卡莎", ccc = "泰坦")
@MyAnnotation2("伊泽")
public class AnnotationTest {@MyAnnotation1(aaa="卡莎",bbb = "艾卡西亚", ccc = "泰坦")public void test1(){}
}
三. 注解的原理
MyAnnotation1.class文件
注解本质是一个接口,Java中所有注解都是继承了Annotation接口的
@注解(....):其实就是一个实现类对象,实现了该注解以及Annotation接口
四. 元注解
元注解:修饰注解的注解。
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface MyAnnotation3 {}
五. 注解的解析
注解的解析:就是判断类上、方法上、成员变量上是否存在注解,并把注解里的内容给解析出来。
Class、Method、Field、Constructor、都实现了AnnotatedElement接口,他们都拥有解析注解的能力。
AnnotatedElement接口提供的解析注解的方法 | 说明 |
public Annotation[] getDeclaredAnnotations() | 获取当前对象上面的注解 |
public T getDeclaredAnnotation(Class<T> annotationClass) | 获取指定的注解对象 |
public boolean isAnnotationPresent(Class<Annotation> annotationClass) | 判断当前对象上面是否存在某个注解 |
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyTest4 {String value();double aaa() default 100;String[] bbb();
}@MyTest4(value = "卡莎", bbb={"q","w", "e", "r"})
public class Demo {@MyTest4(value = "泰坦", bbb={"q","w", "e", "r"})public void test1(){}
}public class AnnotationTest3 {@Testpublic void parseClass() throws NoSuchMethodException {// 解析Demo注解//类Class c = Demo.class;if (c.isAnnotationPresent(MyTest4.class)) {MyTest4 MyTest4 = (MyTest4) c.getDeclaredAnnotation(MyTest4.class);System.out.println(MyTest4.value());System.out.println(MyTest4.aaa());System.out.println(Arrays.toString(MyTest4.bbb()));}//方法 methodMethod m = c.getDeclaredMethod("test1");if (m.isAnnotationPresent(MyTest4.class)) {MyTest4 MyTest4 = (MyTest4) m.getDeclaredAnnotation(MyTest4.class);System.out.println(MyTest4.value());System.out.println(MyTest4.aaa());System.out.println(Arrays.toString(MyTest4.bbb()));}}
}
六. 模拟Junit框架
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTest {
}/*
* 模拟Junit框架
* */
public class Annotation4 {@MyTest()public void test1(){System.out.println("test1");}//@MyTest()public void test2(){System.out.println("test2");}@MyTest()public void test3(){System.out.println("test3");}//@MyTest()public void test4(){System.out.println("test4");}public static void main(String[] args) throws Exception {Annotation4 a = new Annotation4();Class clazz = Annotation4.class;Method[] methods = clazz.getDeclaredMethods();for (Method method : methods) {if (method.isAnnotationPresent(MyTest.class)) {method.invoke(a);}}}
}