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

本文介绍如何使用自定义注解及反射获取注解信息。通过示例展示了如何定义注解、应用注解到类和方法上,并通过反射读取这些注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 这里用了自定义注解,不会的可以先去看看我这篇文章

怎么写注解icon-default.png?t=LA92https://blog.youkuaiyun.com/weixin_57604284/article/details/121420655?spm=1001.2014.3001.5501


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空地址异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值