在下面的代码中
我正在尝试使用我在另一个文件中创建的注释。我不明白为什么我必须编写 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/