通过小案例理解注解的使用

  • 反射注解接口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(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是元注解,改变自定义的注解的存活范围。RUNTIME表示运行时,即可以在程序运行中对其进行访问
//Target也是元注解,指定该注解能用在什么地方。METHOD表示方法前
@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方法超时!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值