isAnnotationPresent() 在 Java 中与超类型引用一起使用时返回 false [英] isAnnotationPresent() return false when used with super type reference in Java
问题描述
我正在尝试使用反射从超类型引用变量中获取注释详细信息,以使该方法接受所有子类型.但是 isAnnotationPresent()
返回 false
.与其他注释相关方法相同.如果在确切类型上使用,则输出符合预期.
I m trying to get the annotation details from super type reference variable using reflection, to make the method accept all sub types. But isAnnotationPresent()
returning false
. Same with other annotation related methods. If used on the exact type, output is as expected.
即使我通过超类型引用,我也知道注释信息将在对象上可用.
I know that annotation info will be available on the Object even I m referring through super type.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Table {
String name();
}
@Table(name = "some_table")
public class SomeEntity {
public static void main(String[] args) {
System.out.println(SomeEntity.class.isAnnotationPresent(Table.class)); // true
System.out.println(new SomeEntity().getClass().isAnnotationPresent(Table.class)); // true
Class<?> o1 = SomeEntity.class;
System.out.println(o1.getClass().isAnnotationPresent(Table.class)); // false
Class<SomeEntity> o2 = SomeEntity.class;
System.out.println(o2.getClass().isAnnotationPresent(Table.class)); // false
Object o3 = SomeEntity.class;
System.out.println(o3.getClass().isAnnotationPresent(Table.class)); // false
}
}
如何获取注解信息?
推荐答案
您正在调用 getClass()
on 一个 Class>
,这将给出 Class
.现在 Class
本身没有注释,这就是为什么你会得到错误.我想你想要:
You're calling getClass()
on a Class<?>
, which will give Class<Class>
. Now Class
itself isn't annotated, which is why you're getting false. I think you want:
// Note no call to o1.getClass()
Class<?> o1 = SomeEntity.class;
System.out.println(o1.isAnnotationPresent(Table.class));
这篇关于isAnnotationPresent() 在 Java 中与超类型引用一起使用时返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!