您好,欢迎来到年旅网。
搜索
您的当前位置:首页JAVA中获取注解对象及注解信息

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
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务