java_annotation_02

通过反射取得Annotation

在一上节中,我们只是简单的创建了Annotation,如果要让一个Annotation起作用,则必须结合反射机制,在Class类上存在以下几种于Annotation有关的方法

-- public <A extends Annotation> A getAnnotation(class<A> annotationClass)

如果在一个元素中存在注释,则取得全部注释

-- public Annotation[] getAnnotations()

返回此元素上所有注释

-- public Annotation[] getDeclaredAnnotations()

返回直接存放在此元素上的所有注释

-- public boolean isAnnotation()

判断元素是否表示一个注释

-- public boolean isAnnotationPersent(Class<? extends Annotation> annotationClass)

判断一个元素上是否存在注释

例一:取得全部的Annotation

1.定义一个具体3个Annotation的类

public class MyTest{
    @SuppressWarnings("unchecked") 
    @Deprecated
    @Override
    public String sayHello(){
        return "Hello WangYang!!!" ;
    }
};

2.想要出得上面的Annotation,则必须首先找到他们属于的方法

import java.lang.annotation.Annotation ;
import java.lang.reflect.Method ;
public class ReflectTest{
    public static void main(String args[]) throws Exception{    // 所有异常抛出
        Class <?> c = null ;
        c = Class.forName("com.wy.MyTest") ;
        Method toM = c.getMethod("sayHello") ;    // 找到sayHello()方法
        Annotation an[] = toM.getAnnotations() ;    // 取得全部的Annotation
        for(Annotation a:an){    // 使用 foreach输出
            System.out.println(a) ;
        }
    }
};

注意:

上面虽然用了3个Annotation,但是最后真正得到的只有一个.这是因为只有@Deprecated使用了RUNTIME的声明方式

例二:我们不单单要取得了一个元素所声明的全部RUNTIME的Annotation,有时需要取得的是某个指定的Annotation,所以此时在取得之前就必须进行明确的判断,使用isAnnotationPresent()方法进行判断.

1.同样定义一个RUNTIME的Annotation

import java.lang.annotation.Retention ;
import java.lang.annotation.RetentionPolicy ;
@Retention(value=RetentionPolicy.RUNTIME)    // 此Annotation在类执行时依然有效
public @interface MyAnnotation{
    public String key() default "wang" ;
    public String value() default "yang" ;

}

2.定义一个类,并使用自定义的Annotation

public class MyAnnotationTest2{
    @SuppressWarnings("unchecked") 
    @Deprecated
    @Override
    @MyDefaultAnnotationReflect(key="wang",value="www.yang.cn")
    public String sayHello(){
        return "Hello WangYang!!!" ;
    }
};

3.取得指定的Annotation

import com.wy.MyAnnotation ;
import java.lang.annotation.Annotation ;
import java.lang.reflect.Method ;
public class MyTest{
    public static void main(String args[]) throws Exception{    // 所有异常抛出
        Class <?> c = null ;
        c = Class.forName("com.wy.MyAnnotationTest2") ;
        Method toM = c.getMethod("sayHello") ;    // 找到sayHello()方法
        if(toM.isAnnotationPresent(MyAnnotation .class)){
            // 判断是否是指定的Annotation
            MyAnnotation mda = null ;
            mda = toM.getAnnotation(MyAnnotation .class) ;    // 得到指定的Annotation
            String key = mda.key() ;    // 取出设置的key
            String value = mda.value() ;    // 取出设置的value
            System.out.println("key = " + key) ;
            System.out.println("value = " + value) ;
        }
    }
};

以上的方式,我们加以合理的应用,就能实现我们想要的注释

原文地址:https://www.cnblogs.com/wangyang108/p/5668462.html