I’ve created an inherited field type annotation that is placed on private properties in an abstract superclass.
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Lifecycle{
Type type();
String name() default "";
public enum Type{
DISCRIMINATOR,INITIAL,MUTABLE
}
}
I’m calling a method from the subclass which seeks to gather all the annotations of this type (inherited or otherwise) and return them in a list.
public static <T extends Annotation> List<T> getAnnotation(final Class c, final Class<T> ann) {
return getAnnotation(c, ann, new ArrayList<T>());
}
public static <T extends Annotation> List<T> getAnnotation(final Class c, final Class<T> ann, List<T> aList) {
Field[] fields = c.getFields();
for (int i = 0; i < fields.length; i++) {
Field myField = fields[i];
myField.setAccessible(true);
T found = myField.getAnnotation(ann);
if (found != null) {
aList.add(found);
}
}
if (!c.getSuperclass().equals(Object.class)) {
return getAnnotation(c.getSuperclass(), ann, aList);
} else {
return aList;
}
}
For some reason unbeknownst to me this doesn’t work. All fields both inherited and not are definitely found. Likewise all classes in the inheritance structure are traversed, but for some reason, myField.getAnnotation(ann); is always null.
I’m kind of at a loss – I don’t understand why if I can properly retrieve the field (as well as get and set it’s value, e.g. not a security thing) that I can’t see it’s annotation.
Instead of this one:
try this:
If this doesn’t work, try to iterate over declared annotations: