一、什么是注解
二、自定义注解
/*** 自定义注解*/public @interface MyAnnotation {String aaa();boolean bbb() default true;String ccc();
}@MyAnnotation ( aaa ="牛魔王",ccc = "sss")
public class Test {@MyAnnotation ( aaa = "aaa",ccc = "666")public void test1(){}}
三、注解的原理
四、元注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention ( RetentionPolicy.RUNTIME )//控制下面的注解一直保留到执行时
@Target ( {ElementType.TYPE,ElementType.METHOD} )//当前被修饰的注解只能用在类上
public @interface MyTest3 {
}
五、注解的解析
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention ( RetentionPolicy.RUNTIME )
@Target ( {ElementType.TYPE,ElementType.METHOD} )
public @interface MyTest4 {String value();double aaa() default 100;String[] bbb();}public class Test4 {@Test//解析Demo类中的全部注解public void parseClass(){//1.先得到Class对象Class c = Demo.class;//2.解析类上的注解//判断一个类上是否有注解if (c.isAnnotationPresent ( MyTest4.class )){MyTest4 myTest4= (MyTest4) c.getDeclaredAnnotation ( MyTest4.class );System.out.println ( myTest4.value () );System.out.println ( myTest4.bbb () );}}}
六、应用场景:模拟Junit框架
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention ( RetentionPolicy.RUNTIME )
@Target ( ElementType.METHOD )
public @interface MyTest {}import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;public class Test2 {@MyTestpublic void test1(){System.out.println ("===========tes1========");}// @MyTestpublic void test2(){System.out.println ("===========tes2========");}// @MyTestpublic void test3(){System.out.println ("===========tes3========");}@MyTestpublic void test4(){System.out.println ("===========tes4========");}public static void main(String[] args) throws Exception {Test2 test = new Test2 ();//1.启动程序//得到Class对象Class c = Test2.class;//2.提取这个类中的全部成员方法Method[] methods = c.getDeclaredMethods ();for (Method method : methods) {if (method.isAnnotationPresent ( MyTest.class )) {//判断当前成员方法是否存在MyTest注解 如果存在 就触发执行method.invoke (test );}}}
}