package com.umanwu.anno03;
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 {
}
package com.umanwu.anno03;
public class Demo {
@MyTest
public void aa() {
System.out.println("aa....");
}
@MyTest
public void bb() {
System.out.println("bb....");
}
@MyTest
public void cc() {
System.out.println("cc....");
}
}
package com.umanwu.anno03;
import java.lang.reflect.Method;
public class TestApp {
public static void main(String[] args) throws Exception{
//模拟 右键运行
// 当前指定类,所有的方法,是否有@MyTest注解,如果有将运行
//1 当前类
Class clazz = Demo.class;
// * new 实例
Object obj = clazz.newInstance();
//2 获得所有的方法
Method[] allMethod = clazz.getMethods();
for(Method method : allMethod){
//3 判断方法上是否有指定的注解
boolean b = method.isAnnotationPresent(MyTest.class);
if(b){
// 4 如果有,运行类
method.invoke(obj);
}
}
}
}
运行结果:

621

被折叠的 条评论
为什么被折叠?



