注解只是一种标识。
常见的注解有:
a、@Override:检查子类确实是覆盖了父类的方法。
b、@Deprecated:说明已经过时了。
c、@SuppressWarnings({ "unused", "deprecation" }):抑制程序中的警告。unused警告的类型。{}数组。all抑制所有警告。
自定义注解:
//元注解:用于修饰注解的注解
//@Retention:作用。改变自定义的注解的存活范围。
@Retention(RetentionPolicy.RUNTIME)
//@Target:作用,指定该注解能用在什么地方
@Target(ElementType.METHOD)
public @interface MyAnnotation {
long timeout() default -1;
}
public class SomeDaoImpl {
@MyAnnotation(timeout=10000)
public void add() {
System.out.println("执行add方法");
}
@MyAnnotation
public void update() {
System.out.println("执行update方法");
}
}
@SuppressWarnings("all")
public class TestRunner {
/*
反射注解类
java.lang.reflect.AnnotatedElement:
<T extends Annotation> T getAnnotation(Class<T> annotationType):得到指定类型的注解引用。没有返回null。
Annotation[] getAnnotations():得到所有的注解,包含从父类继承下来的。
Annotation[] getDeclaredAnnotations():得到自己身上的注解。
boolean isAnnotationPresent(Class<? extends Annotation> annotationType):判断指定的注解有没有。
Class、Method、Field、Constructor等实现了AnnotatedElement接口.
如果:
Class.isAnnotationPresent(MyTest.class):判断类上面有没有@MyTest注解;
Method.isAnnotationPresent(MyTest.class):判断方法上面有没有@MyTest注解。
*/
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
//测试方法是否超时
Class clazz = SomeDaoImpl.class;
Method[] methods = clazz.getMethods();
for (Method method : methods) {
MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
if(anno != null) {
long timeout = anno.timeout(); //获取注解的值
if(timeout < 0) { //表示不需要测试
method.invoke(clazz.newInstance(),null);
}else {
long l1 = System.nanoTime();//获取纳秒
method.invoke(clazz.newInstance(),null);
long l2 = System.nanoTime();//获取纳秒
if((l2-l1) > timeout) {
System.out.println(method.getName()+"方法超时了");
}
}
}
}
}
//模拟Junit
private static void test1() throws IllegalAccessException, InvocationTargetException, InstantiationException {
//通过反射获取类
Class clz = SomeDaoImpl.class;
//获取该类以及父类中的所有方法
Method[] methods = clz.getMethods();
for (Method m : methods) {
//判断该方法上是否含有注解
if(m.isAnnotationPresent(MyAnnotation.class)) {
m.invoke(clz.newInstance(),null);
}
}
}
}