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
    }
}
经验分享 程序员 微信小程序 职场和发展