- 反射注解接口
java.lang.reflect.AnnotatedElement
中有一些与注解相关的方法:
<T extends Annotation> T getAnnotation(Class<T> annotationType)
Annotation[] getAnnotations()
Annotation[] getDeclaredAnnotations()
boolean isAnnotationPresent(Class<? extends Annotation> annotationType)
- Class、Method、Field、Constructor等实现了AnnotatedElement接口。
Class.isAnnotationPresent(MyAnnotation.class)
:判断类上面有没有@MyAnnotation注解;Method.isAnnotationPresent(MyAnnotation.class)
:判断方法上面有没有@MyAnnotation注解。- 下面的示例展示了注解的作用:
public class TestClass {
@MyAnnotation(timeout=1000)
public void testAdd(){
System.out.println("add方法执行了");
}
@MyAnnotation
public void testUpdate(){
System.out.println("update方法执行了");
}
public void testDelete(){
System.out.println("delete方法执行了");
}
}
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 MyAnnotation {
long timeout() default -1;
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Spirit {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException {
Class<TestClass> testClassClass = TestClass.class;
Method[] methods = testClassClass.getMethods();
for (Method m:methods){
MyAnnotation annotation = m.getAnnotation(MyAnnotation.class);
if (annotation!=null){
long timeout = annotation.timeout();
if (timeout<0){
m.invoke(testClassClass.newInstance(),null);
}else{
long l1 = System.nanoTime();
m.invoke(testClassClass.newInstance(), null);
long l2 = System.nanoTime();
if((l2-l1)>timeout){
System.out.println(m.getName()+"方法超时!");
}
}
}
}
}
}
update方法执行了
add方法执行了
testAdd方法超时!