- 先声明一个Test注解
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 Test {
int num();
}
- 这个是测试@Test的类
public class TestAnnotation {
@Test(num = 8)
public void testAdd(){
System.out.println("Hello Add");
}
@Test(num = 12)
public void testDiv(){
System.out.println("Hello Div");
}
}
- @Test的注解处理器
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestRun {
public static void main(String[] args) {
Class<TestAnnotation> c = TestAnnotation.class;
Method[] ms = c.getDeclaredMethods();
for (Method method : ms) {
// method.getAnnotations(); //得到方法上修饰的注解
//遍历test是不是被@Test修饰
if (method.isAnnotationPresent(Test.class)) {
//得到方法上面的@Test注解
Test test = method.getAnnotation(Test.class);
int num = test.num();//得到注解中的num()属性
if (num < 10) {//如果num小于10进入下次循环
continue;
}
try {
//调用方法
method.invoke(c.newInstance());
} catch (IllegalAccessException |
InvocationTargetException |
InstantiationException e) {
e.printStackTrace();
}
}
}
}
}
运行TestRun注解处理器,控制台会输出Hello Div。