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?
In your code,
o1
,o2
ando3
are already theClass<?>
objects on which you'll want to callisAnnotationPresent(Class<?>)
, you shouldn't callgetClass()
on them before, because at this stage, you'll callisAnnotationPresent(Class<?>)
on theClass
class itself, and not on yourSomeEntity
class...First, see
java.lang.annotation.Inherited
.Second, as others pointed out, your code is a bit different from your question.
Third, to answer your question..
I have encountered a similar need many times so I have written a short AnnotationUtil class to do this and some other similar things. Spring framework offers a similar AnnotationUtils class and I suppose dozen other packages today also contain pretty much this piece of code so you don't have to reinvent the wheel.
Anyway this may help you.
The
o1.getClass()
will give you object of typejava.lang.Class
, which doesn't have@Table
annotation. I suppose you wantedo1.isAnnotationPresent(Table.class)
.You're calling
getClass()
on aClass<?>
, which will giveClass<Class>
. NowClass
itself isn't annotated, which is why you're getting false. I think you want: