需求:
定义若干个方法,只要加了MyTest注解,就会触发该方法的执行
分析:
1.定义一个自定义注解MyTest,只能注解方法,存活范围是一直都在
2.定义若干个方法,部分加上@MyTest注解修饰,部分方法不加
3.模拟一个junit程序,可以触发加了@MyTest注解方法的执行
自定义注解:
package my.day02;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)//注解只能注解方法
@Retention(RetentionPolicy.RUNTIME)//当前注解一直存活
public @interface MyTest {
}
测试类: 主方法为实现逻辑 模拟Junit方法上有注解执行该方法,按钮没有通过main方法模拟实现。
package my.day02;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class AnnotationTest4 {
//@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 InvocationTargetException, IllegalAccessException {
AnnotationTest4 a4 = new AnnotationTest4();
//启动程序
//1.得到class类对象
Class test4Class = AnnotationTest4.class;
//2.提取类对象的所有成员方法
Method[] methods = test4Class.getDeclaredMethods();
//3.遍历每个方法看是否有注解 MyTest
for (Method method : methods) {
if (method.isAnnotationPresent(MyTest.class)){
//说明当前方法上面存在注解,触发该方法执行
method.invoke(a4);
}
}
}
}
测试结果: 方法上有注解 的方法得到执行。