JAVA中获取注解对象及注解信息

JAVA中获取注解对象及注解信息

  • 创建注解测试类:
@Annotation04("abc")
public class MyAnnotationTest01 {
    @Annotation04("def")
    public void doSomething(){

    }
}
  • 判断类是否被@Annotation04注解:
    c.isAnnotationPresent(Annotation04.class);

  • 判断doSomething方法是否被@Annotation04注解:
    Method method = c.getDeclaredMethod(“doSomething”);
    System.out.println(method.isAnnotationPresent(Annotation04.class));

  • 获取doSomething上的注解信息

		if (c.isAnnotationPresent(Annotation04.class)){
            //获取该注解对象(类上的)(顺便向下转型变成Annotation04类型)
            Annotation04 myAnnotation = (Annotation04)c.getAnnotation(Annotation04.class);
            System.out.println("类上面的注解对象:" + myAnnotation);
            //获取该类中类上注解的value属性
            System.out.println(myAnnotation.value());
        }
  • 判断String类中是否有Annotation这个注解
    System.out.println(stringClass.isAnnotationPresent(Annotation04.class));

总测试代码:

public class AnnotationTest04 {
    public static void main(String[] args) throws Exception{
        //获取这个类
        Class c = Class.forName("annotation.MyAnnotationTest01");
        //判断类是否被@Annotation04注解
        System.out.println(c.isAnnotationPresent(Annotation04.class));//true

        //判断doSomething方法是否被@Annotation04注解
        Method method = c.getDeclaredMethod("doSomething");
        System.out.println(method.isAnnotationPresent(Annotation04.class));//true
        
		//获取doSomething上的注解信息
        //判断类是否被@Annotation04注解
        if (c.isAnnotationPresent(Annotation04.class)){
            //获取该注解对象(类上的)(顺便向下转型变成Annotation04类型)
            Annotation04 myAnnotation = (Annotation04)c.getAnnotation(Annotation04.class);
            System.out.println("类上面的注解对象:" + myAnnotation);
            //获取该类中类上注解的value属性
            System.out.println(myAnnotation.value());
        }

        Class stringClass = Class.forName("java.lang.String");
        //判断String类中是否有Annotation这个注解
        System.out.println(stringClass.isAnnotationPresent(Annotation04.class));//false
    }
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值