栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

通过反射机制获取指定方法的注解信息

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过反射机制获取指定方法的注解信息

EnumAnnotatedElement接口中的方法
方法功能描述
Annotation getAnnotation(Class annotyple)返回调用对象的注解
Annotation getAnnotations()返回调用对象的所有注解
Annotation getDeclareedAnnotations()返回调用对象的所有非继承注解
Boolean isAnnotationPresent(Class annotyple)判断调用对象关联的注解是由annoType指定的
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno1 {
    String comment();
    int order() default 1;
}
import java.lang.reflect.Method;

//使用自定义的@MyAnno1注解修饰类
@MyAnno1(comment = "类注解")
class MyClass1{
    //使用自定义的@MyAnno1注解修饰方法
    @MyAnno1(comment = "不带参数的方法", order = 2)
    public void myMethod(){

    }
}
public class MyAnno1Demo {
    public static void main(String[] args) throws Exception{
        //获取MyClass1类注解
        MyAnno1 anno1 = MyClass1.class.getAnnotation(MyAnno1.class);
        //输出类注解信息
        System.out.println("MyClass类的注解信息为:" + anno1.comment() + ",序号" + anno1.order());
        //获取MyClass1类的方法myMethod()方法
        Method mth = MyClass1.class.getMethod("myMethod");
        //获取myMethod()方法的注解
        MyAnno1 anno2 = mth.getAnnotation(MyAnno1.class);
        //输出方法注解的信息
        System.out.println("myMethod()方法的注解信息为:" + anno2.comment() + ",序号" + anno2.order());
    }
}

运行结果:

为了能使用反射机制获取注解的相关性息,在定义注解时必须将注解的保留策略设置为RetentionPolicy.RUNTIME,否则获取不到注解对象,程序将会引发NullPointerException空地址异常。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/581787.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号