下面列出了java.lang.reflect.AnnotatedElement#getAnnotation ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Get a single {@link Annotation} of {@code annotationType} from the supplied
* Method, Constructor or Field. Meta-annotations will be searched if the annotation
* is not declared locally on the supplied element.
* @param annotatedElement the Method, Constructor or Field from which to get the annotation
* @param annotationType the annotation type to look for, both locally and as a meta-annotation
* @return the matching annotation, or {@code null} if none found
* @since 3.1
*/
public static <T extends Annotation> T getAnnotation(AnnotatedElement annotatedElement, Class<T> annotationType) {
try {
T ann = annotatedElement.getAnnotation(annotationType);
if (ann == null) {
for (Annotation metaAnn : annotatedElement.getAnnotations()) {
ann = metaAnn.annotationType().getAnnotation(annotationType);
if (ann != null) {
break;
}
}
}
return ann;
}
catch (Exception ex) {
// Assuming nested Class values not resolvable within annotation attributes...
logIntrospectionFailure(annotatedElement, ex);
return null;
}
}
private static List<String> getNames(@Nullable AnnotatedElement outputFunction, AggregationFunction aggregationAnnotation)
{
List<String> defaultNames = ImmutableList.<String>builder().add(aggregationAnnotation.value()).addAll(Arrays.asList(aggregationAnnotation.alias())).build();
if (outputFunction == null) {
return defaultNames;
}
AggregationFunction annotation = outputFunction.getAnnotation(AggregationFunction.class);
if (annotation == null) {
return defaultNames;
}
else {
return ImmutableList.<String>builder().add(annotation.value()).addAll(Arrays.asList(annotation.alias())).build();
}
}
/**
* Given a single-argument method whose parameter is a {@link Collection}, use
* the method's generic type information to determine the collection element
* type and store it as the ITEM_CLASS_NAME attribute of the given Element.
*
* @param method
* the setter method
* @param paramElt
* the PARAMETER element
*/
private void determineCollectionElementType(AnnotatedElement method,
Type paramType, Element paramElt) {
if(paramElt.getAttributeValue("ITEM_CLASS_NAME") == null) {
Class<?> elementType;
CreoleParameter paramAnnot = method.getAnnotation(CreoleParameter.class);
if(paramAnnot != null
&& paramAnnot.collectionElementType() != CreoleParameter.NoElementType.class) {
elementType = paramAnnot.collectionElementType();
} else {
elementType = findCollectionElementType(paramType);
}
if(elementType != null) {
paramElt.setAttribute("ITEM_CLASS_NAME", elementType.getName());
}
}
}
private void addForeignKey(final Attribute<?, ?> jpaAttribute) throws ODataJPAModelException,
ODataJPARuntimeException {
AnnotatedElement annotatedElement = (AnnotatedElement) jpaAttribute.getJavaMember();
joinColumnNames = null;
if (annotatedElement == null) {
return;
}
JoinColumn joinColumn = annotatedElement.getAnnotation(JoinColumn.class);
if (joinColumn == null) {
JoinColumns joinColumns = annotatedElement.getAnnotation(JoinColumns.class);
if (joinColumns != null) {
for (JoinColumn jc : joinColumns.value()) {
buildForeignKey(jc, jpaAttribute);
}
}
} else {
buildForeignKey(joinColumn, jpaAttribute);
}
}
@Override
public Object findSerializer(Annotated a) {
AnnotatedElement ae = a.getAnnotated();
Url an = ae.getAnnotation(Url.class);
if (an == null) {
return null;
}
if (an.type() == String.class) {
return new UriSerializer(an);
} else if (an.type() == List.class) {
return new UrisSerializer(an);
}
throw new UnsupportedOperationException("Unsupported type " + an.type());
}
static Annotation getAnnotation(AnnotatedElement element, String annotationTypeName) {
Class<?> annotationType = null; // Unbounded type token
try {
annotationType = Class.forName(annotationTypeName);
} catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
return element.getAnnotation(annotationType.asSubclass(Annotation.class));
}
private static AccessType getAccessTypeOrNull(AnnotatedElement element) {
if ( element == null ) {
return null;
}
Access elementAccess = element.getAnnotation( Access.class );
return elementAccess == null ? null : elementAccess.value();
}
private void attachValidationAction(PropertyAnnotationHandler handler, PropertyInfo propertyInfo, String fieldName) {
final Method method = propertyInfo.method;
Class<? extends Annotation> annotationType = handler.getAnnotationType();
AnnotatedElement annotationTarget = null;
if (method.getAnnotation(annotationType) != null) {
annotationTarget = method;
} else {
try {
Field field = method.getDeclaringClass().getDeclaredField(fieldName);
if (field.getAnnotation(annotationType) != null) {
annotationTarget = field;
}
} catch (NoSuchFieldException e) {
// ok - ignore
}
}
if (annotationTarget == null) {
return;
}
Annotation optional = annotationTarget.getAnnotation(org.gradle.api.tasks.Optional.class);
if (optional == null) {
propertyInfo.setNotNullValidator(notNullValidator);
}
propertyInfo.attachActions(handler);
}
/**
* Get description of specified element from description parameter of {@link Editable} annotation
*
* @param element
* annotated element to get description from
* @return
* defined description, or <tt>null</tt> if description can not be found
*/
public static @Nullable String getDescription(AnnotatedElement element) {
Editable editable = element.getAnnotation(Editable.class);
if (editable != null) {
if (editable.description().length() != 0)
return editable.description();
}
return null;
}
private static String getNameOfEmptyValue(AnnotatedElement element) {
NameOfEmptyValue nameOfEmptyValue = element.getAnnotation(NameOfEmptyValue.class);
if (nameOfEmptyValue != null)
return HtmlEscape.escapeHtml5(nameOfEmptyValue.value());
else
return "Not defined";
}
public WebServiceRefElement(Member member, AnnotatedElement ae, PropertyDescriptor pd) {
super(member, pd);
WebServiceRef resource = ae.getAnnotation(WebServiceRef.class);
String resourceName = resource.name();
Class<?> resourceType = resource.type();
this.isDefaultName = !StringUtils.hasLength(resourceName);
if (this.isDefaultName) {
resourceName = this.member.getName();
if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) {
resourceName = Introspector.decapitalize(resourceName.substring(3));
}
}
if (resourceType != null && Object.class != resourceType) {
checkResourceType(resourceType);
}
else {
// No resource type specified... check field/method.
resourceType = getResourceType();
}
this.name = resourceName;
this.elementType = resourceType;
if (Service.class.isAssignableFrom(resourceType)) {
this.lookupType = resourceType;
}
else {
this.lookupType = resource.value();
}
this.mappedName = resource.mappedName();
this.wsdlLocation = resource.wsdlLocation();
}
@Override
@Nullable
public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
javax.ejb.TransactionAttribute ann = element.getAnnotation(javax.ejb.TransactionAttribute.class);
if (ann != null) {
return parseTransactionAnnotation(ann);
}
else {
return null;
}
}
private String getSchemaDocumentation(AnnotatedElement annotatedElement) {
if (annotatedElement != null) {
SchemaDocumentation schemaDocumentation = annotatedElement.getAnnotation(SchemaDocumentation.class);
return schemaDocumentation != null ? schemaDocumentation.value() : null;
}
return null;
}
public static boolean shouldBeIgnored(AnnotatedElement annotatedElement) {
return annotatedElement.getAnnotation(OpenApiIgnore.class) != null;
}
private void extractJoinColumns() {
/*
* Check against Static Buffer whether the join column was already
* extracted.
*/
if (!jpaAttribute.equals(bufferedJPAAttribute)) {
bufferedJPAAttribute = jpaAttribute;
bufferedJoinColumns.clear();
} else if (bufferedJoinColumns.isEmpty()) {
roleExists = false;
return;
} else {
roleExists = true;
return;
}
AnnotatedElement annotatedElement = (AnnotatedElement) jpaAttribute
.getJavaMember();
if (annotatedElement == null) {
return;
}
JoinColumn joinColumn = annotatedElement
.getAnnotation(JoinColumn.class);
if (joinColumn == null) {
JoinColumns joinColumns = annotatedElement
.getAnnotation(JoinColumns.class);
if (joinColumns != null) {
JoinColumn[] joinColumnArray = joinColumns.value();
for (JoinColumn element : joinColumnArray) {
bufferedJoinColumns.add(element);
}
} else {
return;
}
} else {
bufferedJoinColumns.add(joinColumn);
}
roleExists = true;
}
@Override
public Object getValue(@NotNull Object adaptable, String name, @NotNull Type declaredType, @NotNull AnnotatedElement element,
@NotNull DisposalCallbackRegistry callbackRegistry) {
String[] resourcePaths = null;
Path pathAnnotation = element.getAnnotation(Path.class);
ResourcePath resourcePathAnnotation = element.getAnnotation(ResourcePath.class);
if (pathAnnotation != null) {
resourcePaths = getPathsFromAnnotation(pathAnnotation);
} else if (resourcePathAnnotation != null) {
resourcePaths = getPathsFromAnnotation(resourcePathAnnotation);
}
if (ArrayUtils.isEmpty(resourcePaths) && name != null) {
// try the valuemap
ValueMap map = getValueMap(adaptable);
if (map != null) {
resourcePaths = map.get(name, String[].class);
}
}
if (ArrayUtils.isEmpty(resourcePaths)) {
// could not find a path to inject
return null;
}
ResourceResolver resolver = getResourceResolver(adaptable);
if (resolver == null) {
return null;
}
List<Resource> resources = getResources(resolver, resourcePaths, name);
if (resources == null || resources.isEmpty()) {
return null;
}
// unwrap/wrap if necessary
if (isDeclaredTypeCollection(declaredType)) {
return resources;
} if (declaredType instanceof Class<?> && ((Class<?>)declaredType).isArray()){
return resources.toArray(new Resource[0]);
}
if (resources.size() == 1) {
return resources.get(0);
} else {
// multiple resources to inject, but field is not a list
LOG.warn("Cannot inject multiple resources into field {} since it is not declared as a list", name);
return null;
}
}
public boolean matches(AnnotatedElement element) {
Annotation fromElement = element.getAnnotation(annotation.annotationType());
return fromElement != null && annotation.equals(fromElement);
}
@Override
public boolean matches(AnnotatedElement element) {
return element.getAnnotation(annotationType) != null;
}
/**
* 从某个类上获取注解对象,注解可以深度递归
* 如果存在多个继承注解,则优先获取浅层第一个注解,如果浅层不存在,则返回第一个获取到的注解
* 请尽可能保证仅存在一个或者一种继承注解,否则获取到的类型将不可控
*
* @param from 获取注解的某个类
* @param annotationType 想要获取的注解类型
* @param ignored 获取注解列表的时候的忽略列表
* @return 获取到的第一个注解对象
*/
public static <T extends Annotation> T getAnnotation(AnnotatedElement from, Class<T> annotationType, Class<T>... ignored) {
// 首先尝试获取缓存
T cache = getCache(from, annotationType);
if(cache != null){
return cache;
}
if(isNull(from, annotationType)){
return null;
}
//先尝试直接获取
T annotation = from.getAnnotation(annotationType);
//如果存在直接返回,否则查询
if (annotation != null) {
saveCache(from, annotation);
return annotation;
}
// 获取target注解
Target target = annotationType.getAnnotation(Target.class);
// 判断这个注解能否标注在其他注解上,如果不能,则不再深入获取
boolean annotationable = false;
if (target != null) {
for (ElementType elType : target.value()) {
if (elType == ElementType.TYPE || elType == ElementType.ANNOTATION_TYPE) {
annotationable = true;
break;
}
}
}
Annotation[] annotations = from.getAnnotations();
annotation = annotationable ? getAnnotationFromArrays(annotations, annotationType, ignored) : null;
// 如果还是获取不到,看看查询的注解类型有没有对应的ByNameType
if (annotation == null) {
annotation = getByNameAnnotation(from, annotationType);
}
// 如果无法通过注解本身所指向的byName注解获取,看看有没有反向指向此类型的注解
// 此情况下不进行深层获取
if(annotation == null){
annotation = getAnnotationFromByNames(annotations, annotationType);
}
// 如果最终不是null,计入缓存
if(annotation != null){
saveCache(from, annotation);
}else{
nullCache(from, annotationType);
}
return annotation;
}
/**
* Get icon of specified element from icon parameter of {@link Editable} annotation.
*
* @param element
* annotated element to get icon from
* @return
* icon name of specified element, or <tt>null</tt> if not defined
*/
public static @Nullable String getIcon(AnnotatedElement element) {
Editable editable = element.getAnnotation(Editable.class);
if (editable != null && editable.icon().trim().length() != 0)
return editable.icon();
else
return null;
}