[Java] annotationType()和getClass() 在 Java 11 中的区别

先自己写个注解:

@Retention(RUNTIME)
public @interface TestAnno {
	String value() default "nul";
}

再进行测试:

@TestAnno
public class Test {
	public static void main(String[] args) throws Exception {
		var a = Test.class.getAnnotation(TestAnno.class);	
		
		var intr = a.annotationType();
		var im = intr.getMethod("value");
		System.out.println(im.invoke(a));
		
		var proxy = a.getClass();
		var pm = proxy.getMethod("value");
		System.out.println(pm.invoke(a));
	}
}

输出结果如下:

nul
Exception in thread "main" java.lang.IllegalAccessException: class info.tozzger.test.Test (in module info.tozzger.test) cannot access class com.sun.proxy.jdk.proxy1.$Proxy1 (in module jdk.proxy1) because module jdk.proxy1 does not export com.sun.proxy.jdk.proxy1 to module info.tozzger.test
	at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
	at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
	at java.base/java.lang.reflect.Method.invoke(Method.java:558)
	at info.tozzger.test/info.tozzger.test.Test.main(Test.java:14)

因此,在高版本的 JDK 中,应该使用 annotationType() 对注解进行操作。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据