java - Field#getAnnotations() 和 Field#getDeclaredAnnotations() 之间的区别

标签 java inheritance annotations

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.

Field#getAnnotations :

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/

相关文章:

java - 如何使用 Ant 创建 postgresql 数据库?

java - 在 jFrame 中显示来自 jTable 的数据

java - 使用 Maven 将公共(public)文件夹添加到我的两个模块

C++ VaSTLy 不同的派生类 - 虚拟方法? Actor ?

java - JSR-305 的 JSR-308 扩展?

java - 需要帮助来理解此开关代码 - 月份中的日子

java - 方法检索和继承困惑

java - 如何让所有主要方法显示执行时间

ios - 自定义 MGLAnnotationView

mysql - Hibernate 映射中的 OneToMany 和 ManyToOne