java - Java中的注解为什么要创建类类型引用?

标签 java jakarta-ee

在下面的代码中

我正在尝试使用我在另一个文件中创建的注释。我不明白为什么我必须编写 Class c=test.getClass(); 因为我已经创建了 TEST 类的对象,那么为什么需要这个?我尝试不使用这个 Class c=test.getClass(); 但它显示错误

public static void showAnnotations()
     // Function to show annotation information
     {
         TEST test=new TEST(); // Instantiating Test class
         try
         {
             Class c=test.getClass(); // Getting Class reference
             java.lang.reflect.Method m=c.getMethod("testMethod"); // Getting Method reference
             // Getting Class annotation
             MyAnnotation annotation1=
               (MyAnnotation)c.getAnnotation(MyAnnotation.class);
             // Getting Method annotation
             MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class);
             // Displaying annotation information
             System.out.println("Author of the class: "+annotation1.author());
             // Displaying annotation information
             System.out.println("Date of Writing the class: "+annotation1.date());
             // Displaying annotation information
             System.out.println("Author of the method: "+annotation2.author());
             // Displaying annotation information
             System.out.println("Date of Writing the method: "+annotation2.date());
         }
         catch(NoSuchMethodException ex)
         {
             System.out.println("Invalid Method..."+ex.getMessage());
         }
     }

最佳答案

当您调用 getClass 时,您正在使用 code reflection这意味着您在程序中使用的数据包含有关程序本身的信息。

是的,您有一个由 test 引用的 TEST 类的对象。您可以使用其方法或访问其公共(public)属性。也就是说,您有一个 TEST 类的实例,您开发该实例是为了使用 OOP 范式表示某些信息。

另一方面,您需要一个对程序本身进行建模的对象:代表您的类的类的实例。 Java 提供了有关其他类的类建模信息:Class 类。

因此,您需要请求一个代表您的 TEST 类的 Class 实例。这是你的台词:

Class c=test.getClass();

您还可以使用以下行来获取此实例:

Class c=TEST.class;

关于java - Java中的注解为什么要创建类类型引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23042062/

相关文章:

javascript - Javascript 将 json 文件中的数据存储到 map 中?

java - splunk检查消息是否包含特定字符串

Java 条件配置 (web.xml) - 开发/生产

java - 如何在@Stateless bean中设置@WebMethod的超时值?

web-applications - 将 EJB 和接口(interface)拆分为单独的模块——部署失败

java - 如何解决 Debugger has detached;对象注册表在 android studio 中有 1 个条目

java - 如何得到拓扑排序的所有解

java - Maven 和 native 库文件

jsp - 我的 servlet 中的编码问题

java - 如何在 ZUL 文件中使用 HTML 标签