[Java] java反射 显示所有注释类和方法(在运行时使用反射获取注解) →→→→→进入此内容的聊天室

来自 , 2021-03-12, 写在 Java, 查看 111 次.
URL http://www.code666.cn/view/7f1171a7
  1. //显示所有注释类和方法
  2. import java.lang.annotation.*;
  3. import java.lang.reflect.*;
  4.  
  5. @Retention(RetentionPolicy.RUNTIME)
  6. @interface MyAnno {
  7.   String str();
  8.   int val();
  9. }
  10.  
  11. @Retention(RetentionPolicy.RUNTIME)
  12. @interface What {
  13.   String description();
  14. }
  15.  
  16. @What(description = "An annotation test class")
  17. @MyAnno(str = "Meta2", val = 99)
  18. class Meta2 {
  19.  
  20.   @What(description = "An annotation test method")
  21.   @MyAnno(str = "Testing", val = 100)
  22.  
  23.   public static void myMeth() {
  24.     Meta2 ob = new Meta2();
  25.  
  26.     try {
  27.       Annotation annos[] = ob.getClass().getAnnotations();
  28.  
  29.       // Display all annotations for Meta2.
  30.       System.out.println("All annotations for Meta2:");
  31.       for(Annotation a : annos)
  32.         System.out.println(a);
  33.  
  34.       System.out.println();
  35.  
  36.     // Display all annotations for myMeth.
  37.     Method m = ob.getClass( ).getMethod("myMeth");
  38.     annos = m.getAnnotations();
  39.  
  40.     System.out.println("All annotations for myMeth:");
  41.     for(Annotation a : annos)
  42.       System.out.println(a);
  43.     } catch (NoSuchMethodException exc) {
  44.        System.out.println("Method Not Found.");
  45.     }
  46.   }
  47.  
  48.   public static void main(String args[]) {
  49.     myMeth();
  50.   }
  51. }

回复 "java反射 显示所有注释类和方法(在运行时使用反射获取注解)"

这儿你可以回复上面这条便签

captcha