反射与annotation

1,可以通过反射取得使用的全部annotation

2,可以通过反射取得指定的annotation。

一个annotation要想变得有意义, 必须结合反射机制取得annotation中设置的全部内容。

以下是反射取得annotation相关方法:

如下:设置了三个annotation,那么此时,只有Deprecated的annotation的定义范围是RUNTIME的。

package 类集;

public class SimpleBeanOne{
    @SuppressWarnings("unchecked") 
    @Deprecated
    @Override
    public String toString(){
        return "Hello LiXingHua!!!" ;
    }
};

复习:

因为只有Deprecated是RUNTIME定义范围,也就是执行时候出现。

那么通过反射的话只能取得一个。

取得annotation:

package 类集;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class ReflectDemo01 {

    public static void main(String args[]) throws Exception{    // 所有异常抛出
        Class <?> c = null ;
        c = Class.forName("类集.SimpleBeanOne") ;
        Method toM = c.getMethod("toString") ;    // 找到toString()方法
        Annotation an[] = toM.getAnnotations() ;    // 取得全部的Annotation
        for(Annotation a:an){    // 使用 foreach输出
            System.out.println(a) ;
        }
    }

}

输出结果:

@java.lang.Deprecated()

此时已经取得了一个annotation。

可以发现,上面是通过反射取得一个Method对象,然后通过这个Method对象获取这个方法所拥有的annotation。

以上操作代码实际上是通过三个系统内建的annotation完成的。那么也可以自定义annotation。

自定义一个注释annotation

package 类集;
import java.lang.annotation.Retention ;
import java.lang.annotation.RetentionPolicy ;//指定范围
@Retention(value
=RetentionPolicy.RUNTIME) // 此Annotation在类执行时依然有效,注意,这个value值是RetentionPolicy的枚举值 public @interface MyDefaultAnnotationReflect{ public String key() default "LXH" ; public String value() default "李兴华" ; }

以上annotation范围在执行时候有效,下面定义一个类使用此annotation。

package org.lxh.demo16.reflectannotation ;//指定范围。
public class SimpleBeanTwo{
    @SuppressWarnings("unchecked") 
    @Deprecated
    @Override
    @MyDefaultAnnotationReflect(key="MLDN",value="www.mldnjava.cn")
    public String toString(){
        return "Hello LiXingHua!!!" ;
    }
};

使用反射取得指定的annotation,因为现在唯一设置内容的就是MyDefaultAnnotationReflect

package 类集;

import java.lang.reflect.Method;
public class ReflectDemo02 {

    public static void main(String args[]) throws Exception{    // 所有异常抛出
        Class <?> c = null ;
        c = Class.forName("类集.SimpleBeanTwo") ;
        Method toM = c.getMethod("toString") ;    // 找到toString()方法
        if(toM.isAnnotationPresent(MyDefaultAnnotationReflect.class)){
            // 判断是否是指定的Annotation
            MyDefaultAnnotationReflect mda = null ;
            mda = toM.getAnnotation(MyDefaultAnnotationReflect.class) ;    // 得到指定的Annotation
            String key = mda.key() ;    // 取出设置的key
            String value = mda.value() ;    // 取出设置的value
            System.out.println("key = " + key) ;
            System.out.println("value = " + value) ;
        }
    }
}

输出:

key = MLDN
value = www.mldnjava.cn

上文发现,annotation可以通过key(),value()方法取得所设置的变量名和变量值

  annotation在实际中,不管如何使用,最终肯定是结合反射机制,也就是说可以通过annotation设置一些内容到方法上去,以完成特点功能。

原文地址:https://www.cnblogs.com/alsf/p/6667075.html