温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么利用反射取得Annotation信息

发布时间:2021-06-22 17:14:03 来源:亿速云 阅读:106 作者:Leah 栏目:编程语言

本篇文章为大家展示了怎么利用反射取得Annotation信息,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

获取Annotation信息

在进行类或方法定义时,都可以使用一系列的Annotation进行声明,于是如果要想获得这些Annotation信息,那么可以直接通过反射来完成。在java.lang.reflect里面有一个AccessibleObject类,在本类中提供有获取Annotation类的方法:

获取全部Annotation:
public Annotation[] getAnnotations()
获取指定Annotation:
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)

怎么利用反射取得Annotation信息

范例:定义一个接口,并在接口在使用Annotation

import java.io.Serializable;import java.lang.annotation.Annotation;import java.lang.reflect.Method;public class JavaAPIDemo {public static void main(String[] args) throws Exception {
        {   //获取接口上的Annotation信息Annotation annotations [] = IMessage.class.getAnnotations();  //获取接口上的全部Annotationfor (Annotation temp : annotations) {
                System.out.println(temp);//@java.lang.FunctionalInterface()//@java.lang.Deprecated(forRemoval=false, since="1.0")}
        }
        System.out.println("-----------------------");
        {//获取MessageImpl子类上的Annotation信息Annotation annotations []= MessageImpl.class.getAnnotations();  //获取类上的全部Annotationfor (Annotation temp : annotations) {
                System.out.println(temp);
            }
        }
        System.out.println("-----------------------");
        {   //获取MessageImpl.toString()方法上的Annotation信息Method method = MessageImpl.class.getDeclaredMethod("send", String.class);Annotation annotations [] = method.getAnnotations();  for (Annotation temp : annotations) {
                System.out.println(temp);
            }
        }
    }
}@FunctionalInterface    //程序执行时可以获取@Deprecated(since = "1.0")     interface IMessage {     //有2个Annotationpublic void send(String msg);
}@SuppressWarnings("serial")     //无法在程序执行时获取class MessageImpl implements IMessage, Serializable {@Override      //无法在程序执行时获取public void send(String msg) {
        System.out.println("【消息发送】" + msg);
    }
}

不同的Annotation有它的存在范围,下面对比两个Annotation:
@FunctionalInterface(运行时):

@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)
public @interface FunctionalInterface {}

@SuppressWarnings(源代码):

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, MODULE})@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {}

现在发现“@FunctionalInterface”是在运行时生效的Annotation,所以程序执行时可以获取Annotation;而“@SuppressWarnings”是在源代码编写时有效。
在RetentionPolicy枚举类中还有一个class的定义,指的是在类定义时生效。

自定义Annotation

现在已经清楚了Annotation的获取,以及Annotation的运行策略,但是最为关键性的因素是如何实现自定义的Annotation呢?为此在Java中提供了新的语法,使用“@interface”来定义Annotation。
范例:自定义Annotation

import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method;@Retention(RetentionPolicy.RUNTIME)   //定义Annotation的运行策略@interface DefaultAnnotation {      //自定义的Annotationpublic String title();      //获取数据public String url() default "www.mldn.cn";   //获取数据class Message {@DefaultAnnotation(title = "MLDN")public void send(String msg) {
        System.out.println("【消息发送】" + msg);
    }
}public class JavaAPIDemo {public static void main(String[] args) throws Exception {
        Method method = Message.class.getMethod("send",String.class);  //获取指定方法DefaultAnnotation  anno = method.getAnnotation(DefaultAnnotation.class);  //获取指定的Annotation//System.out.println(anno.title());  //直接调用Annotation中的方法  MLDN//System.out.println(anno.url());    //直接调用Annotation中的方法  www.mldn.cn//直接调用Annotation中的方法String msg = anno.title()+"("+anno.url()+")";  //消息内容 method.invoke(Message.class.getDeclaredConstructor().newInstance(), msg);   //【消息发送】MLDN(www.mldn.cn)}
}

使用Annotation之后的最大特点是可以结合反射机制实现程序的处理。

上述内容就是怎么利用反射取得Annotation信息,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI