directly present的定义:直接标注在类上的注解
indirectly present的定义:如果一个类E上有一个注解容器,而该注解容器中包含有A类型的注解,那么A注解就是indirectly出现在E上
present的定义:如果注解A直接出现在类E上,或者类E上没有直接标注A,但是E的父类上标注有A,并且注解A是可继承的,那么A就present在E上
associated的定义:A直接或间接出现在E上,以及E的父类与A关联(associated),并且A是可继承的,那么A便与E关联(associated)
Method | Kind of Presence | ||||
---|---|---|---|---|---|
Return Type | Signature | Directly Present | Indirectly Present | Present | Associated |
{@code T} | {@link #getAnnotation(Class) getAnnotation(Class<T>)} | √ | |||
{@code Annotation[]} | {@link #getAnnotations getAnnotations()} | √ | |||
{@code T[]} | {@link #getAnnotationsByType(Class) getAnnotationsByType(Class<T>)} | √ | |||
{@code T} | {@link #getDeclaredAnnotation(Class) getDeclaredAnnotation(Class<T>)} | √ | |||
{@code Annotation[]} | {@link #getDeclaredAnnotations getDeclaredAnnotations()} | √ | |||
{@code T[]} | {@link #getDeclaredAnnotationsByType(Class) getDeclaredAnnotationsByType(Class<T>)} | √ | √ |
public interface AnnotatedElement {
/**
* 判断该类上是present指定的注解,即该类或其父类上是否直接出现指定的父类
*/
default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
return getAnnotation(annotationClass) != null;
}
/**
*获取present在该类上的具有指定类型的注解对象,不存在则返回null
*/
<T extends Annotation> T getAnnotation(Class<T> annotationClass);
/**
* 获取present在该类上所有的注解对象,没有则返回长度为0的数组
*/
Annotation[] getAnnotations();
/**
*获取所有相关的(associated)注解元素
*/
default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
//
T[] result = getDeclaredAnnotationsByType(annotationClass);
if (result.length == 0 && // Neither directly nor indirectly present
this instanceof Class && // the element is a class
AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
Class<?> superClass = ((Class<?>) this).getSuperclass();
if (superClass != null) {
// Determine if the annotation is associated with the
// superclass
result = superClass.getAnnotationsByType(annotationClass);
}
}
return result;
}
/**
* 获取directly出现在在该类上的注解
*/
default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
Objects.requireNonNull(annotationClass);
// Loop over all directly-present annotations looking for a matching one
for (Annotation annotation : getDeclaredAnnotations()) {
if (annotationClass.equals(annotation.annotationType())) {
// More robust to do a dynamic cast at runtime instead
// of compile-time only.
return annotationClass.cast(annotation);
}
}
return null;
}
/**
*获取directly或indirectly出现在该类上的注解
*/
default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
Objects.requireNonNull(annotationClass);
return AnnotationSupport.
getDirectlyAndIndirectlyPresent(Arrays.stream(getDeclaredAnnotations()). collect(Collectors.toMap(Annotation::annotationType, unction.identity(),
((first,second) -> first),LinkedHashMap::new)),annotationClass);
}
/**
* 获取所有直接标注在当前类上的注解(directly present)
*/
Annotation[] getDeclaredAnnotations();
}