判断指定注解是否存在: boolean annotationPresent = method.isAnnotationPresent(MyAnnotation.class);
1. 自定义注解:MyAnnotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
2、使用:MyAnnotationDemo
@Deprecated
public class MyAnnotationDemo {
@MyAnnotation
public void print()
{
System.out.println("call print()");
}
}
3. 测试类
public class MyAnnotationDemoTest {
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("com.demo.annotation.MyAnnotationDemo");
printClassInfo(clazz);
Method[] methods = clazz.getMethods();
printMethodInfo(clazz, methods);
}
private static void printClassInfo(Class<?> clazz) { for (Annotation annotation : clazz.getAnnotations()) {
System.out.println("class annotation name: " + annotation.toString());
}
}
private static void printMethodInfo(Class<?> clazz, Method[] methods) throws Exception { for (Method method : methods) {
// 判断方法是否有指定的注解信息
boolean annotationPresent = method.isAnnotationPresent(MyAnnotation.class);
if (annotationPresent) {
System.out.println(method.getName());
// 反射方式调用当前方法
method.invoke(clazz.getConstructor(null).newInstance(null), null);
method.invoke(clazz.newInstance(), null);
for (Annotation annotation : method.getAnnotations()) {
System.out.println("method annotation: " + annotation.toString());
}
}
}
}
}
4. 测试结果:
class annotation name: @java.lang.Deprecated()
print
call print()
call print()
method annotation: @com.demo.annotation.MyAnnotation()