JavaDoc 说明如下:
AccessibleObject#getDeclaredAnnotations :
Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.
Returns all annotations present on this element. (Returns an array of length zero if this element has no annotations.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.
由于 getAnnotations
是从 java.lang.reflect.AccessibleObject
类继承而来的,所以 Field 对象可以访问它。
据我所知,它们之间的唯一区别是 getDeclaredAnnotations
会忽略继承的注释。 我在处理类时明白这一点,但据我所知,字段不能继承注释。
最佳答案
查看源代码给出了答案:
摘自 java.lang.reflect.AccessibleObject :
/**
* @since 1.5
*/
public Annotation[] getAnnotations() {
return getDeclaredAnnotations();
}
/**
* @since 1.5
*/
public Annotation[] getDeclaredAnnotations() {
throw new AssertionError("All subclasses should override this method");
}
自 Field does not override getAnnotations()
: getDeclaredAnnotations()
被调用。
因此,当在 java.lang.reflect.Field
对象上调用时,这两种方法的作用相同。
(所以我认为 JavaDoc 是错误的)
另一种情况是java.lang.Class它覆盖了这两种方法(并执行它的 JavaDoc 所说的 ;)):
/**
* @since 1.5
*/
public Annotation[] getAnnotations() {
initAnnotationsIfNecessary();
return AnnotationParser.toArray(annotations);
}
/**
* @since 1.5
*/
public Annotation[] getDeclaredAnnotations() {
initAnnotationsIfNecessary();
return AnnotationParser.toArray(declaredAnnotations);
}
关于java - Field#getAnnotations() 和 Field#getDeclaredAnnotations() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18512304/