IsAnnotationPresent () returns false when used with a super-type reference in Java

I am trying to get annotation details from a supertype reference variable using reflection to force the method to accept all subtypes. But isAnnotationPresent()returns false. Same thing with other annotation-related methods. If the exact type is used, the output will be as expected.

I know that annotation information will be available on the object, even if I reference the supertype.

@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 annotation information?

+5
source share
4 answers

getClass() Class<?>, Class<Class>. Class , . , :

// Note no call to o1.getClass()
Class<?> o1 = SomeEntity.class;
System.out.println(o1.isAnnotationPresent(Table.class));
+13

. java.lang.annotation.Inherited.

-, , .

-, ..

, AnnotationUtil . Spring framework AnnotationUtils, , , , .

.

public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> annotationType) {
    T result = clazz.getAnnotation(annotationType);
    if (result == null) {
        Class<?> superclass = clazz.getSuperclass();
        if (superclass != null) {
            return getAnnotation(superclass, annotationType);
        } else {
            return null;
        }
    } else {
        return result;
    }
}
+3

o1.getClass() java.lang.Class, @Table. , o1.isAnnotationPresent(Table.class).

+2

o1, o2 o3 Class<?>, isAnnotationPresent(Class<?>), getClass() , isAnnotationPresent(Class<?>) Class, SomeEntity...

+1

All Articles