在Java超类型参考使用时isAnnotation present()返回false [英] isAnnotationPresent() return false when used with super type reference in Java
问题描述
我试图让从超类型的引用变量使用反射,使该方法接受所有子类型的标注的详细信息。但 isAnnotation present()
返回假
。同样与其他注释相关的方法。如果确切类型使用,如预期的输出。
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
}
}
如何获得注释信息?
How to get the annotation info?
推荐答案
您正在呼叫的getClass()
的在的一个类&LT;&GT;
,这将给类&LT;班级&GT;
。现在类
本身的不的注释,这就是为什么你得到错误的。我想你想要的:
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));
这篇关于在Java超类型参考使用时isAnnotation present()返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!