在抽象超类上找不到继承注释
我创建了一个继承的字段类型注释,该注释放置在抽象超类中的私有属性上。
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Lifecycle{
Type type();
String name() default "";
public enum Type{
DISCRIMINATOR,INITIAL,MUTABLE
}
}
我正在从子类调用一个方法,该方法旨在收集该类型的所有注释(继承或其他)并将它们返回到列表中。
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;
}
}
由于某种我不知道的原因,这不起作用。所有继承的和未继承的字段都肯定会找到。同样,继承结构中的所有类都会被遍历,但由于某种原因,myField.getAnnotation(ann);
始终为 null。
我有点不知所措 - 我不明白为什么如果我可以正确检索该字段(以及获取和设置它的值,例如不是安全的东西),我看不到它的注释。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而不是这个:
尝试这个:
如果这不起作用,请尝试迭代声明的注释:
Instead of this one:
try this:
If this doesn't work, try to iterate over declared annotations: