/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import org.springframework.core.BridgeMethodResolver; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; /** * General utility methods for working with annotations, handling bridge methods * (which the compiler generates for generic declarations) as well as super methods * (for optional "annotation inheritance"). Note that none of this is * provided by the JDK's introspection facilities themselves. * *
As a general rule for runtime-retained annotations (e.g. for transaction
* control, authorization, or service exposure), always use the lookup methods
* on this class (e.g., {@link #findAnnotation(Method, Class)},
* {@link #getAnnotation(Method, Class)}, and {@link #getAnnotations(Method)})
* instead of the plain annotation lookup methods in the JDK. You can still
* explicitly choose between a get lookup on the given class level only
* ({@link #getAnnotation(Method, Class)}) and a find lookup in the entire
* inheritance hierarchy of the given method ({@link #findAnnotation(Method, Class)}).
*
* @author Rob Harrop
* @author Juergen Hoeller
* @author Sam Brannen
* @author Mark Fisher
* @author Chris Beams
* @author Phillip Webb
* @since 2.0
* @see java.lang.reflect.Method#getAnnotations()
* @see java.lang.reflect.Method#getAnnotation(Class)
*/
public abstract class AnnotationUtils {
/** The attribute name for annotations with a single element */
static final String VALUE = "value";
private static final Map Correctly handles bridge {@link Method Methods} generated by the compiler.
* @param method the method to look for annotations on
* @return the annotations found
* @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
*/
public static Annotation[] getAnnotations(Method method) {
return BridgeMethodResolver.findBridgedMethod(method).getAnnotations();
}
/**
* Get a single {@link Annotation} of {@code annotationType} from the supplied {@link Method}.
* Correctly handles bridge {@link Method Methods} generated by the compiler.
* @param method the method to look for annotations on
* @param annotationType the annotation class to look for
* @return the annotations found
* @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
*/
public static A getAnnotation(Method method, Class annotationType) {
Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
return getAnnotation((AnnotatedElement) resolvedMethod, annotationType);
}
/**
* Get the possibly repeating {@link Annotation}s of {@code annotationType} from the
* supplied {@link Method}. Deals with both a single direct annotation and repeating
* annotations nested within a containing annotation.
* Correctly handles bridge {@link Method Methods} generated by the compiler.
* @param method the method to look for annotations on
* @param containerAnnotationType the class of the container that holds the annotations
* @param annotationType the annotation class to look for
* @return the annotations found
* @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
* @since 4.0
*/
public static Set getRepeatableAnnotation(Method method,
Class extends Annotation> containerAnnotationType, Class annotationType) {
Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
return getRepeatableAnnotation((AnnotatedElement) resolvedMethod,
containerAnnotationType, annotationType);
}
/**
* Get the possibly repeating {@link Annotation}s of {@code annotationType} from the
* supplied {@link AnnotatedElement}. Deals with both a single direct annotation and
* repeating annotations nested within a containing annotation.
* Correctly handles bridge {@link Method Methods} generated by the compiler.
* @param annotatedElement the element to look for annotations on
* @param containerAnnotationType the class of the container that holds the annotations
* @param annotationType the annotation class to look for
* @return the annotations found
* @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
* @since 4.0
*/
public static Set getRepeatableAnnotation(AnnotatedElement annotatedElement,
Class extends Annotation> containerAnnotationType, Class annotationType) {
if (annotatedElement.getAnnotations().length == 0) {
return Collections.emptySet();
}
return new AnnotationCollector(containerAnnotationType, annotationType).getResult(annotatedElement);
}
/**
* Find a single {@link Annotation} of {@code annotationType} from the supplied
* {@link Method}, traversing its super methods (i.e., from super classes and
* interfaces) if no annotation can be found on the given method itself.
* Annotations on methods are not inherited by default, so we need to handle
* this explicitly.
* @param method the method to look for annotations on
* @param annotationType the annotation class to look for
* @return the annotation found, or {@code null} if none found
*/
public static A findAnnotation(Method method, Class annotationType) {
A annotation = getAnnotation(method, annotationType);
Class> clazz = method.getDeclaringClass();
if (annotation == null) {
annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
}
while (annotation == null) {
clazz = clazz.getSuperclass();
if (clazz == null || clazz.equals(Object.class)) {
break;
}
try {
Method equivalentMethod = clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
annotation = getAnnotation(equivalentMethod, annotationType);
}
catch (NoSuchMethodException ex) {
// No equivalent method found
}
if (annotation == null) {
annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
}
}
return annotation;
}
private static A searchOnInterfaces(Method method, Class annotationType, Class>[] ifcs) {
A annotation = null;
for (Class> iface : ifcs) {
if (isInterfaceWithAnnotatedMethods(iface)) {
try {
Method equivalentMethod = iface.getMethod(method.getName(), method.getParameterTypes());
annotation = getAnnotation(equivalentMethod, annotationType);
}
catch (NoSuchMethodException ex) {
// Skip this interface - it doesn't have the method...
}
if (annotation != null) {
break;
}
}
}
return annotation;
}
private static boolean isInterfaceWithAnnotatedMethods(Class> iface) {
synchronized (annotatedInterfaceCache) {
Boolean flag = annotatedInterfaceCache.get(iface);
if (flag != null) {
return flag;
}
boolean found = false;
for (Method ifcMethod : iface.getMethods()) {
if (ifcMethod.getAnnotations().length > 0) {
found = true;
break;
}
}
annotatedInterfaceCache.put(iface, found);
return found;
}
}
/**
* Find a single {@link Annotation} of {@code annotationType} from the supplied
* {@link Class}, traversing its annotations, interfaces, and superclasses if
* no annotation can be found on the given class itself.
* This method explicitly handles class-level annotations which are not
* declared as {@link java.lang.annotation.Inherited inherited} as well
* as meta-annotations and annotations on interfaces.
* The algorithm operates as follows:
* If the supplied {@code clazz} is an interface, only the interface itself will be checked;
* the inheritance hierarchy for interfaces will not be traversed.
* The standard {@link Class} API does not provide a mechanism for determining which class
* in an inheritance hierarchy actually declares an {@link Annotation}, so we need to handle
* this explicitly.
* @param annotationType the annotation class to look for, both locally and as a meta-annotation
* @param clazz the class on which to check for the annotation, or {@code null}
* @return the first {@link Class} in the inheritance hierarchy of the specified {@code clazz}
* which declares an annotation for the specified {@code annotationType}, or {@code null}
* if not found
* @see Class#isAnnotationPresent(Class)
* @see Class#getDeclaredAnnotations()
* @see #findAnnotationDeclaringClassForTypes(List, Class)
* @see #isAnnotationDeclaredLocally(Class, Class)
*/
public static Class> findAnnotationDeclaringClass(Class extends Annotation> annotationType, Class> clazz) {
Assert.notNull(annotationType, "Annotation type must not be null");
if (clazz == null || clazz.equals(Object.class)) {
return null;
}
if (isAnnotationDeclaredLocally(annotationType, clazz)) {
return clazz;
}
return findAnnotationDeclaringClass(annotationType, clazz.getSuperclass());
}
/**
* Find the first {@link Class} in the inheritance hierarchy of the specified
* {@code clazz} (including the specified {@code clazz} itself) which declares
* at least one of the specified {@code annotationTypes}, or {@code null} if
* none of the specified annotation types could be found.
* If the supplied {@code clazz} is {@code null}, {@code null} will be
* returned.
* If the supplied {@code clazz} is an interface, only the interface itself
* will be checked; the inheritance hierarchy for interfaces will not be traversed.
* The standard {@link Class} API does not provide a mechanism for determining
* which class in an inheritance hierarchy actually declares one of several
* candidate {@linkplain Annotation annotations}, so we need to handle this
* explicitly.
* @param annotationTypes the list of Class objects corresponding to the
* annotation types
* @param clazz the Class object corresponding to the class on which to check
* for the annotations, or {@code null}
* @return the first {@link Class} in the inheritance hierarchy of the specified
* {@code clazz} which declares an annotation of at least one of the specified
* {@code annotationTypes}, or {@code null} if not found
* @since 3.2.2
* @see Class#isAnnotationPresent(Class)
* @see Class#getDeclaredAnnotations()
* @see #findAnnotationDeclaringClass(Class, Class)
* @see #isAnnotationDeclaredLocally(Class, Class)
*/
public static Class> findAnnotationDeclaringClassForTypes(List Note: This method does not determine if the annotation is
* {@linkplain java.lang.annotation.Inherited inherited}. For greater clarity
* regarding inherited annotations, consider using
* {@link #isAnnotationInherited(Class, Class)} instead.
* @param annotationType the Class object corresponding to the annotation type
* @param clazz the Class object corresponding to the class on which to check for the annotation
* @return {@code true} if an annotation for the specified {@code annotationType}
* is declared locally on the supplied {@code clazz}
* @see Class#getDeclaredAnnotations()
* @see #isAnnotationInherited(Class, Class)
*/
public static boolean isAnnotationDeclaredLocally(Class extends Annotation> annotationType, Class> clazz) {
Assert.notNull(annotationType, "Annotation type must not be null");
Assert.notNull(clazz, "Class must not be null");
boolean declaredLocally = false;
for (Annotation annotation : clazz.getDeclaredAnnotations()) {
if (annotation.annotationType().equals(annotationType)) {
declaredLocally = true;
break;
}
}
return declaredLocally;
}
/**
* Determine whether an annotation for the specified {@code annotationType} is present
* on the supplied {@code clazz} and is {@linkplain java.lang.annotation.Inherited inherited}
* (i.e., not declared locally for the class).
* If the supplied {@code clazz} is an interface, only the interface itself will be checked.
* In accordance with standard meta-annotation semantics, the inheritance hierarchy for interfaces
* will not be traversed. See the {@linkplain java.lang.annotation.Inherited Javadoc} for the
* {@code @Inherited} meta-annotation for further details regarding annotation inheritance.
* @param annotationType the Class object corresponding to the annotation type
* @param clazz the Class object corresponding to the class on which to check for the annotation
* @return {@code true} if an annotation for the specified {@code annotationType} is present
* on the supplied {@code clazz} and is inherited
* @see Class#isAnnotationPresent(Class)
* @see #isAnnotationDeclaredLocally(Class, Class)
*/
public static boolean isAnnotationInherited(Class extends Annotation> annotationType, Class> clazz) {
Assert.notNull(annotationType, "Annotation type must not be null");
Assert.notNull(clazz, "Class must not be null");
return (clazz.isAnnotationPresent(annotationType) && !isAnnotationDeclaredLocally(annotationType, clazz));
}
/**
* Retrieve the given annotation's attributes as a Map, preserving all attribute types
* as-is.
* Note: As of Spring 3.1.1, the returned map is actually an
* {@link AnnotationAttributes} instance, however the Map signature of this method has
* been preserved for binary compatibility.
* @param annotation the annotation to retrieve the attributes for
* @return the Map of annotation attributes, with attribute names as keys and
* corresponding attribute values as values
*/
public static Map Note: As of Spring 3.1.1, the returned map is actually an
* {@link AnnotationAttributes} instance, however the Map signature of this method has
* been preserved for binary compatibility.
* @param annotation the annotation to retrieve the attributes for
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @return the Map of annotation attributes, with attribute names as keys and
* corresponding attribute values as values
*/
public static Map
*
* @param clazz the class to look for annotations on
* @param annotationType the annotation class to look for
* @return the annotation found, or {@code null} if none found
*/
public static A findAnnotation(Class> clazz, Class annotationType) {
Assert.notNull(clazz, "Class must not be null");
A annotation = clazz.getAnnotation(annotationType);
if (annotation != null) {
return annotation;
}
for (Class> ifc : clazz.getInterfaces()) {
annotation = findAnnotation(ifc, annotationType);
if (annotation != null) {
return annotation;
}
}
if (!Annotation.class.isAssignableFrom(clazz)) {
for (Annotation ann : clazz.getAnnotations()) {
annotation = findAnnotation(ann.annotationType(), annotationType);
if (annotation != null) {
return annotation;
}
}
}
Class> superClass = clazz.getSuperclass();
if (superClass == null || superClass.equals(Object.class)) {
return null;
}
return findAnnotation(superClass, annotationType);
}
/**
* Find the first {@link Class} in the inheritance hierarchy of the specified {@code clazz}
* (including the specified {@code clazz} itself) which declares an annotation for the
* specified {@code annotationType}, or {@code null} if not found. If the supplied
* {@code clazz} is {@code null}, {@code null} will be returned.
*