AnnotationUtils.java 33.2 KB
Newer Older
A
Arjen Poutsma 已提交
1
/*
2
 * Copyright 2002-2015 the original author or authors.
A
Arjen Poutsma 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * 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;
20
import java.lang.reflect.AnnotatedElement;
A
Arjen Poutsma 已提交
21
import java.lang.reflect.Method;
22 23 24 25
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
26
import java.util.List;
A
Arjen Poutsma 已提交
27
import java.util.Map;
28
import java.util.Set;
A
Arjen Poutsma 已提交
29

30 31 32
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

A
Arjen Poutsma 已提交
33 34
import org.springframework.core.BridgeMethodResolver;
import org.springframework.util.Assert;
35
import org.springframework.util.ConcurrentReferenceHashMap;
36
import org.springframework.util.ObjectUtils;
37
import org.springframework.util.ReflectionUtils;
38
import org.springframework.util.StringUtils;
A
Arjen Poutsma 已提交
39 40

/**
S
Sam Brannen 已提交
41 42 43 44
 * 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.
A
Arjen Poutsma 已提交
45
 *
S
Sam Brannen 已提交
46 47 48 49 50 51 52 53
 * <p>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 <em>get</em> lookup on the given class level only
 * ({@link #getAnnotation(Method, Class)}) and a <em>find</em> lookup in the entire
 * inheritance hierarchy of the given method ({@link #findAnnotation(Method, Class)}).
A
Arjen Poutsma 已提交
54 55 56 57 58
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @author Mark Fisher
C
Chris Beams 已提交
59
 * @author Chris Beams
60
 * @author Phillip Webb
A
Arjen Poutsma 已提交
61 62 63 64 65 66 67
 * @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 */
68
	public static final String VALUE = "value";
A
Arjen Poutsma 已提交
69

70

71 72 73 74 75
	private static final Map<AnnotationCacheKey, Annotation> findAnnotationCache =
			new ConcurrentReferenceHashMap<AnnotationCacheKey, Annotation>(256);

	private static final Map<Class<?>, Boolean> annotatedInterfaceCache =
			new ConcurrentReferenceHashMap<Class<?>, Boolean>(256);
76

77 78
	private static transient Log logger;

J
Juergen Hoeller 已提交
79

80 81 82 83
	/**
	 * Get a single {@link Annotation} of {@code annotationType} from the supplied
	 * annotation: either the given annotation itself or a meta-annotation thereof.
	 * @param ann the Annotation to check
J
Juergen Hoeller 已提交
84 85
	 * @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
86 87 88 89 90 91 92
	 * @since 4.0
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Annotation> T getAnnotation(Annotation ann, Class<T> annotationType) {
		if (annotationType.isInstance(ann)) {
			return (T) ann;
		}
93 94 95 96 97
		try {
			return ann.annotationType().getAnnotation(annotationType);
		}
		catch (Exception ex) {
			// Assuming nested Class values not resolvable within annotation attributes...
98
			logIntrospectionFailure(ann.annotationType(), ex);
99 100
			return null;
		}
101 102
	}

103
	/**
C
Chris Beams 已提交
104 105 106
	 * 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.
107
	 * @param annotatedElement the Method, Constructor or Field from which to get the annotation
J
Juergen Hoeller 已提交
108 109
	 * @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
C
Chris Beams 已提交
110
	 * @since 3.1
111
	 */
112
	public static <T extends Annotation> T getAnnotation(AnnotatedElement annotatedElement, Class<T> annotationType) {
113
		try {
114
			T ann = annotatedElement.getAnnotation(annotationType);
115
			if (ann == null) {
116
				for (Annotation metaAnn : annotatedElement.getAnnotations()) {
117 118 119 120
					ann = metaAnn.annotationType().getAnnotation(annotationType);
					if (ann != null) {
						break;
					}
121 122
				}
			}
123 124 125 126
			return ann;
		}
		catch (Exception ex) {
			// Assuming nested Class values not resolvable within annotation attributes...
127
			logIntrospectionFailure(annotatedElement, ex);
128
			return null;
129 130 131
		}
	}

132 133 134
	/**
	 * Get all {@link Annotation Annotations} from the supplied Method, Constructor or Field.
	 * @param annotatedElement the Method, Constructor or Field to retrieve annotations from
135 136
	 * @return the annotations found, or {@code null} if not resolvable (e.g. because nested
	 * Class values in annotation attributes failed to resolve at runtime)
137 138 139 140 141 142 143 144 145 146 147 148 149
	 * @since 4.0.8
	 */
	public static Annotation[] getAnnotations(AnnotatedElement annotatedElement) {
		try {
			return annotatedElement.getAnnotations();
		}
		catch (Exception ex) {
			// Assuming nested Class values not resolvable within annotation attributes...
			logIntrospectionFailure(annotatedElement, ex);
			return null;
		}
	}

A
Arjen Poutsma 已提交
150 151 152
	/**
	 * Get all {@link Annotation Annotations} from the supplied {@link Method}.
	 * <p>Correctly handles bridge {@link Method Methods} generated by the compiler.
153
	 * @param method the Method to retrieve annotations from
A
Arjen Poutsma 已提交
154 155 156 157
	 * @return the annotations found
	 * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
	 */
	public static Annotation[] getAnnotations(Method method) {
158 159 160 161 162
		try {
			return BridgeMethodResolver.findBridgedMethod(method).getAnnotations();
		}
		catch (Exception ex) {
			// Assuming nested Class values not resolvable within annotation attributes...
163
			logIntrospectionFailure(method, ex);
164 165
			return null;
		}
A
Arjen Poutsma 已提交
166 167 168
	}

	/**
169
	 * Get a single {@link Annotation} of {@code annotationType} from the supplied {@link Method}.
A
Arjen Poutsma 已提交
170 171
	 * <p>Correctly handles bridge {@link Method Methods} generated by the compiler.
	 * @param method the method to look for annotations on
J
Juergen Hoeller 已提交
172
	 * @param annotationType the annotation type to look for
A
Arjen Poutsma 已提交
173 174 175 176
	 * @return the annotations found
	 * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
	 */
	public static <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {
177
		Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
178
		return getAnnotation((AnnotatedElement) resolvedMethod, annotationType);
A
Arjen Poutsma 已提交
179 180
	}

181 182 183 184 185 186 187
	/**
	 * 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.
	 * <p>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
J
Juergen Hoeller 已提交
188
	 * @param annotationType the annotation type to look for
189 190
	 * @return the annotations found
	 * @since 4.0
J
Juergen Hoeller 已提交
191
	 * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
192 193 194
	 */
	public static <A extends Annotation> Set<A> getRepeatableAnnotation(Method method,
			Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) {
J
Juergen Hoeller 已提交
195

196
		Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
J
Juergen Hoeller 已提交
197
		return getRepeatableAnnotation((AnnotatedElement) resolvedMethod, containerAnnotationType, annotationType);
198 199 200 201 202 203 204 205 206
	}

	/**
	 * 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.
	 * <p>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
J
Juergen Hoeller 已提交
207
	 * @param annotationType the annotation type to look for
208 209
	 * @return the annotations found
	 * @since 4.0
J
Juergen Hoeller 已提交
210
	 * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
211 212 213
	 */
	public static <A extends Annotation> Set<A> getRepeatableAnnotation(AnnotatedElement annotatedElement,
			Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) {
J
Juergen Hoeller 已提交
214

215 216 217 218
		try {
			if (annotatedElement.getAnnotations().length > 0) {
				return new AnnotationCollector<A>(containerAnnotationType, annotationType).getResult(annotatedElement);
			}
219
		}
220 221
		catch (Exception ex) {
			// Assuming nested Class values not resolvable within annotation attributes...
222
			logIntrospectionFailure(annotatedElement, ex);
223 224
		}
		return Collections.emptySet();
225 226
	}

A
Arjen Poutsma 已提交
227
	/**
S
Sam Brannen 已提交
228
	 * Find a single {@link Annotation} of {@code annotationType} from the supplied
J
Juergen Hoeller 已提交
229
	 * {@link Method}, traversing its super methods (i.e., from superclasses and
S
Sam Brannen 已提交
230 231 232
	 * interfaces) if no annotation can be found on the given method itself.
	 * <p>Annotations on methods are not inherited by default, so we need to handle
	 * this explicitly.
A
Arjen Poutsma 已提交
233
	 * @param method the method to look for annotations on
J
Juergen Hoeller 已提交
234 235
	 * @param annotationType the annotation type to look for
	 * @return the annotation found, or {@code null} if none
A
Arjen Poutsma 已提交
236
	 */
237
	@SuppressWarnings("unchecked")
A
Arjen Poutsma 已提交
238
	public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) {
239 240 241 242 243 244 245
		AnnotationCacheKey cacheKey = new AnnotationCacheKey(method, annotationType);
		A result = (A) findAnnotationCache.get(cacheKey);
		if (result == null) {
			result = getAnnotation(method, annotationType);
			Class<?> clazz = method.getDeclaringClass();
			if (result == null) {
				result = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
A
Arjen Poutsma 已提交
246
			}
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
			while (result == null) {
				clazz = clazz.getSuperclass();
				if (clazz == null || clazz.equals(Object.class)) {
					break;
				}
				try {
					Method equivalentMethod = clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
					result = getAnnotation(equivalentMethod, annotationType);
				}
				catch (NoSuchMethodException ex) {
					// No equivalent method found
				}
				if (result == null) {
					result = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
				}
262
			}
263 264
			if (result != null) {
				findAnnotationCache.put(cacheKey, result);
A
Arjen Poutsma 已提交
265 266
			}
		}
267
		return result;
A
Arjen Poutsma 已提交
268 269
	}

270
	private static <A extends Annotation> A searchOnInterfaces(Method method, Class<A> annotationType, Class<?>... ifcs) {
271
		A annotation = null;
J
Juergen Hoeller 已提交
272
		for (Class<?> iface : ifcs) {
273 274 275 276 277 278 279 280 281 282 283
			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;
				}
284
			}
285 286 287 288 289
		}
		return annotation;
	}

	private static boolean isInterfaceWithAnnotatedMethods(Class<?> iface) {
290 291 292 293 294 295 296 297 298 299
		Boolean flag = annotatedInterfaceCache.get(iface);
		if (flag != null) {
			return flag;
		}
		boolean found = false;
		for (Method ifcMethod : iface.getMethods()) {
			try {
				if (ifcMethod.getAnnotations().length > 0) {
					found = true;
					break;
300
				}
301 302 303
			}
			catch (Exception ex) {
				// Assuming nested Class values not resolvable within annotation attributes...
304
				logIntrospectionFailure(ifcMethod, ex);
305 306
			}
		}
307 308
		annotatedInterfaceCache.put(iface, found);
		return found;
309 310
	}

A
Arjen Poutsma 已提交
311
	/**
312 313 314 315
	 * Find a single {@link Annotation} of {@code annotationType} on the
	 * supplied {@link Class}, traversing its interfaces, annotations, and
	 * superclasses if the annotation is not <em>present</em> on the given class
	 * itself.
S
Sam Brannen 已提交
316
	 * <p>This method explicitly handles class-level annotations which are not
317 318
	 * declared as {@link java.lang.annotation.Inherited inherited} <em>as well
	 * as meta-annotations and annotations on interfaces</em>.
S
Sam Brannen 已提交
319 320
	 * <p>The algorithm operates as follows:
	 * <ol>
321 322
	 * <li>Search for the annotation on the given class and return it if found.
	 * <li>Recursively search through all annotations that the given class declares.
323
	 * <li>Recursively search through all interfaces that the given class declares.
324
	 * <li>Recursively search through the superclass hierarchy of the given class.
S
Sam Brannen 已提交
325
	 * </ol>
326 327 328
	 * <p>Note: in this context, the term <em>recursively</em> means that the search
	 * process continues by returning to step #1 with the current interface,
	 * annotation, or superclass as the class to look for annotations on.
A
Arjen Poutsma 已提交
329
	 * @param clazz the class to look for annotations on
330 331
	 * @param annotationType the type of annotation to look for
	 * @return the annotation if found, or {@code null} if not found
A
Arjen Poutsma 已提交
332
	 */
333
	@SuppressWarnings("unchecked")
A
Arjen Poutsma 已提交
334
	public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) {
335 336 337 338 339 340 341 342 343
		AnnotationCacheKey cacheKey = new AnnotationCacheKey(clazz, annotationType);
		A result = (A) findAnnotationCache.get(cacheKey);
		if (result == null) {
			result = findAnnotation(clazz, annotationType, new HashSet<Annotation>());
			if (result != null) {
				findAnnotationCache.put(cacheKey, result);
			}
		}
		return result;
344 345 346 347 348
	}

	/**
	 * Perform the search algorithm for {@link #findAnnotation(Class, Class)},
	 * avoiding endless recursion by tracking which annotations have already
S
Sam Brannen 已提交
349
	 * been <em>visited</em>.
350 351
	 * @param clazz the class to look for annotations on
	 * @param annotationType the type of annotation to look for
S
Sam Brannen 已提交
352
	 * @param visited the set of annotations that have already been visited
353 354
	 * @return the annotation if found, or {@code null} if not found
	 */
355
	@SuppressWarnings("unchecked")
J
Juergen Hoeller 已提交
356
	private static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType, Set<Annotation> visited) {
A
Arjen Poutsma 已提交
357
		Assert.notNull(clazz, "Class must not be null");
358 359 360 361 362 363 364

		try {
			Annotation[] anns = clazz.getDeclaredAnnotations();
			for (Annotation ann : anns) {
				if (ann.annotationType().equals(annotationType)) {
					return (A) ann;
				}
365
			}
366 367 368 369 370 371
			for (Annotation ann : anns) {
				if (!isInJavaLangAnnotationPackage(ann) && visited.add(ann)) {
					A annotation = findAnnotation(ann.annotationType(), annotationType, visited);
					if (annotation != null) {
						return annotation;
					}
372
				}
373
			}
A
Arjen Poutsma 已提交
374
		}
375 376
		catch (Exception ex) {
			// Assuming nested Class values not resolvable within annotation attributes...
377
			logIntrospectionFailure(clazz, ex);
378 379 380
			return null;
		}

A
Arjen Poutsma 已提交
381
		for (Class<?> ifc : clazz.getInterfaces()) {
382
			A annotation = findAnnotation(ifc, annotationType, visited);
A
Arjen Poutsma 已提交
383 384 385 386
			if (annotation != null) {
				return annotation;
			}
		}
387

388 389
		Class<?> superclass = clazz.getSuperclass();
		if (superclass == null || superclass.equals(Object.class)) {
A
Arjen Poutsma 已提交
390 391
			return null;
		}
S
Sam Brannen 已提交
392
		return findAnnotation(superclass, annotationType, visited);
A
Arjen Poutsma 已提交
393 394 395
	}

	/**
396 397 398 399 400
	 * 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.
	 * <p>If the supplied {@code clazz} is an interface, only the interface itself will be checked;
J
Juergen Hoeller 已提交
401 402 403 404
	 * the inheritance hierarchy for interfaces will not be traversed.
	 * <p>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.
J
Juergen Hoeller 已提交
405 406
	 * @param annotationType the annotation type to look for, both locally and as a meta-annotation
	 * @param clazz the class on which to check for the annotation (may be {@code null})
407 408
	 * @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}
J
Juergen Hoeller 已提交
409
	 * if not found
A
Arjen Poutsma 已提交
410 411
	 * @see Class#isAnnotationPresent(Class)
	 * @see Class#getDeclaredAnnotations()
412 413
	 * @see #findAnnotationDeclaringClassForTypes(List, Class)
	 * @see #isAnnotationDeclaredLocally(Class, Class)
A
Arjen Poutsma 已提交
414 415 416 417 418 419
	 */
	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;
		}
420 421 422 423
		if (isAnnotationDeclaredLocally(annotationType, clazz)) {
			return clazz;
		}
		return findAnnotationDeclaringClass(annotationType, clazz.getSuperclass());
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
	}

	/**
	 * 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.
	 * <p>If the supplied {@code clazz} is {@code null}, {@code null} will be
	 * returned.
	 * <p>If the supplied {@code clazz} is an interface, only the interface itself
	 * will be checked; the inheritance hierarchy for interfaces will not be traversed.
	 * <p>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
446
	 * @since 3.2.2
447 448 449 450 451
	 * @see Class#isAnnotationPresent(Class)
	 * @see Class#getDeclaredAnnotations()
	 * @see #findAnnotationDeclaringClass(Class, Class)
	 * @see #isAnnotationDeclaredLocally(Class, Class)
	 */
452
	public static Class<?> findAnnotationDeclaringClassForTypes(List<Class<? extends Annotation>> annotationTypes, Class<?> clazz) {
453 454 455 456 457 458 459 460 461 462
		Assert.notEmpty(annotationTypes, "The list of annotation types must not be empty");
		if (clazz == null || clazz.equals(Object.class)) {
			return null;
		}
		for (Class<? extends Annotation> annotationType : annotationTypes) {
			if (isAnnotationDeclaredLocally(annotationType, clazz)) {
				return clazz;
			}
		}
		return findAnnotationDeclaringClassForTypes(annotationTypes, clazz.getSuperclass());
A
Arjen Poutsma 已提交
463 464 465
	}

	/**
466 467
	 * Determine whether an annotation for the specified {@code annotationType} is
	 * declared locally on the supplied {@code clazz}. The supplied {@link Class}
J
Juergen Hoeller 已提交
468 469
	 * may represent any type.
	 * <p>Note: This method does <strong>not</strong> determine if the annotation is
S
Sam Brannen 已提交
470 471 472
	 * {@linkplain java.lang.annotation.Inherited inherited}. For greater clarity
	 * regarding inherited annotations, consider using
	 * {@link #isAnnotationInherited(Class, Class)} instead.
A
Arjen Poutsma 已提交
473
	 * @param annotationType the Class object corresponding to the annotation type
J
Juergen Hoeller 已提交
474
	 * @param clazz the Class object corresponding to the class on which to check for the annotation
475 476
	 * @return {@code true} if an annotation for the specified {@code annotationType}
	 * is declared locally on the supplied {@code clazz}
A
Arjen Poutsma 已提交
477 478 479 480 481 482 483
	 * @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;
484
		try {
485 486
			for (Annotation ann : clazz.getDeclaredAnnotations()) {
				if (ann.annotationType().equals(annotationType)) {
487 488 489
					declaredLocally = true;
					break;
				}
A
Arjen Poutsma 已提交
490 491
			}
		}
492 493
		catch (Exception ex) {
			// Assuming nested Class values not resolvable within annotation attributes...
494
			logIntrospectionFailure(clazz, ex);
495
		}
A
Arjen Poutsma 已提交
496 497 498 499
		return declaredLocally;
	}

	/**
500
	 * Determine whether an annotation for the specified {@code annotationType} is present
S
Sam Brannen 已提交
501 502
	 * on the supplied {@code clazz} and is {@linkplain java.lang.annotation.Inherited inherited}
	 * (i.e., not declared locally for the class).
503
	 * <p>If the supplied {@code clazz} is an interface, only the interface itself will be checked.
J
Juergen Hoeller 已提交
504
	 * In accordance with standard meta-annotation semantics, the inheritance hierarchy for interfaces
S
Sam Brannen 已提交
505 506
	 * will not be traversed. See the {@linkplain java.lang.annotation.Inherited Javadoc} for the
	 * {@code @Inherited} meta-annotation for further details regarding annotation inheritance.
A
Arjen Poutsma 已提交
507
	 * @param annotationType the Class object corresponding to the annotation type
J
Juergen Hoeller 已提交
508
	 * @param clazz the Class object corresponding to the class on which to check for the annotation
509
	 * @return {@code true} if an annotation for the specified {@code annotationType} is present
S
Sam Brannen 已提交
510
	 * on the supplied {@code clazz} and is <em>inherited</em>
A
Arjen Poutsma 已提交
511 512 513 514 515 516 517 518 519
	 * @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));
	}

520
	/**
J
Juergen Hoeller 已提交
521
	 * Determine if the supplied {@link Annotation} is defined in the core JDK
522
	 * {@code java.lang.annotation} package.
J
Juergen Hoeller 已提交
523
	 * @param annotation the annotation to check (never {@code null})
524 525 526 527 528 529 530
	 * @return {@code true} if the annotation is in the {@code java.lang.annotation} package
	 */
	public static boolean isInJavaLangAnnotationPackage(Annotation annotation) {
		Assert.notNull(annotation, "Annotation must not be null");
		return annotation.annotationType().getName().startsWith("java.lang.annotation");
	}

A
Arjen Poutsma 已提交
531
	/**
J
Juergen Hoeller 已提交
532 533 534 535
	 * Retrieve the given annotation's attributes as a {@link Map}, preserving all
	 * attribute types as-is.
	 * <p>Note: This method actually returns an {@link AnnotationAttributes} instance.
	 * However, the {@code Map} signature has been preserved for binary compatibility.
A
Arjen Poutsma 已提交
536
	 * @param annotation the annotation to retrieve the attributes for
J
Juergen Hoeller 已提交
537 538
	 * @return the Map of annotation attributes, with attribute names as keys and
	 * corresponding attribute values as values
A
Arjen Poutsma 已提交
539 540
	 */
	public static Map<String, Object> getAnnotationAttributes(Annotation annotation) {
541
		return getAnnotationAttributes(annotation, false, false);
542 543 544
	}

	/**
J
Juergen Hoeller 已提交
545 546
	 * Retrieve the given annotation's attributes as a {@link Map}. Equivalent to
	 * calling {@link #getAnnotationAttributes(Annotation, boolean, boolean)} with
547
	 * the {@code nestedAnnotationsAsMap} parameter set to {@code false}.
J
Juergen Hoeller 已提交
548 549
	 * <p>Note: This method actually returns an {@link AnnotationAttributes} instance.
	 * However, the {@code Map} signature has been preserved for binary compatibility.
550
	 * @param annotation the annotation to retrieve the attributes for
551
	 * @param classValuesAsString whether to turn Class references into Strings (for
J
Juergen Hoeller 已提交
552 553
	 * compatibility with {@link org.springframework.core.type.AnnotationMetadata}
	 * or to preserve them as Class references
J
Juergen Hoeller 已提交
554 555
	 * @return the Map of annotation attributes, with attribute names as keys and
	 * corresponding attribute values as values
556
	 */
557
	public static Map<String, Object> getAnnotationAttributes(Annotation annotation, boolean classValuesAsString) {
558 559 560 561 562
		return getAnnotationAttributes(annotation, classValuesAsString, false);
	}

	/**
	 * Retrieve the given annotation's attributes as an {@link AnnotationAttributes}
J
Juergen Hoeller 已提交
563 564 565
	 * map structure.
	 * <p>This method provides fully recursive annotation reading capabilities on par with
	 * the reflection-based {@link org.springframework.core.type.StandardAnnotationMetadata}.
566 567
	 * @param annotation the annotation to retrieve the attributes for
	 * @param classValuesAsString whether to turn Class references into Strings (for
J
Juergen Hoeller 已提交
568 569
	 * compatibility with {@link org.springframework.core.type.AnnotationMetadata}
	 * or to preserve them as Class references
570 571 572 573 574 575 576 577
	 * @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
	 * {@link AnnotationAttributes} maps (for compatibility with
	 * {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
	 * Annotation instances
	 * @return the annotation attributes (a specialized Map) with attribute names as keys
	 * and corresponding attribute values as values
	 * @since 3.1.1
	 */
578 579
	public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, boolean classValuesAsString,
			boolean nestedAnnotationsAsMap) {
580 581

		AnnotationAttributes attrs = new AnnotationAttributes();
A
Arjen Poutsma 已提交
582
		Method[] methods = annotation.annotationType().getDeclaredMethods();
583
		for (Method method : methods) {
A
Arjen Poutsma 已提交
584 585
			if (method.getParameterTypes().length == 0 && method.getReturnType() != void.class) {
				try {
586
					ReflectionUtils.makeAccessible(method);
587
					Object value = method.invoke(annotation);
588
					attrs.put(method.getName(), adaptValue(value, classValuesAsString, nestedAnnotationsAsMap));
A
Arjen Poutsma 已提交
589 590 591 592 593 594 595 596 597
				}
				catch (Exception ex) {
					throw new IllegalStateException("Could not obtain annotation attribute values", ex);
				}
			}
		}
		return attrs;
	}

598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
	/**
	 * Adapt the given value according to the given class and nested annotation settings.
	 * @param value the annotation attribute value
	 * @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
	 * @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
	 * {@link AnnotationAttributes} maps (for compatibility with
	 * {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
	 * Annotation instances
	 * @return the adapted value, or the original value if no adaptation is needed
	 */
	static Object adaptValue(Object value, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
		if (classValuesAsString) {
			if (value instanceof Class) {
				value = ((Class<?>) value).getName();
			}
			else if (value instanceof Class[]) {
				Class<?>[] clazzArray = (Class[]) value;
				String[] newValue = new String[clazzArray.length];
				for (int i = 0; i < clazzArray.length; i++) {
					newValue[i] = clazzArray[i].getName();
				}
				value = newValue;
			}
		}
		if (nestedAnnotationsAsMap && value instanceof Annotation) {
			return getAnnotationAttributes((Annotation) value, classValuesAsString, true);
		}
		else if (nestedAnnotationsAsMap && value instanceof Annotation[]) {
			Annotation[] realAnnotations = (Annotation[]) value;
			AnnotationAttributes[] mappedAnnotations = new AnnotationAttributes[realAnnotations.length];
			for (int i = 0; i < realAnnotations.length; i++) {
				mappedAnnotations[i] = getAnnotationAttributes(realAnnotations[i], classValuesAsString, true);
			}
			return mappedAnnotations;
		}
		else {
			return value;
		}
	}

A
Arjen Poutsma 已提交
640
	/**
641
	 * Retrieve the <em>value</em> of the {@code &quot;value&quot;} attribute of a
J
Juergen Hoeller 已提交
642
	 * single-element Annotation, given an annotation instance.
A
Arjen Poutsma 已提交
643
	 * @param annotation the annotation instance from which to retrieve the value
644
	 * @return the attribute value, or {@code null} if not found
A
Arjen Poutsma 已提交
645 646 647 648 649 650 651
	 * @see #getValue(Annotation, String)
	 */
	public static Object getValue(Annotation annotation) {
		return getValue(annotation, VALUE);
	}

	/**
J
Juergen Hoeller 已提交
652
	 * Retrieve the <em>value</em> of a named attribute, given an annotation instance.
A
Arjen Poutsma 已提交
653 654
	 * @param annotation the annotation instance from which to retrieve the value
	 * @param attributeName the name of the attribute value to retrieve
655
	 * @return the attribute value, or {@code null} if not found
J
Juergen Hoeller 已提交
656
	 * @see #getValue(Annotation)
A
Arjen Poutsma 已提交
657 658
	 */
	public static Object getValue(Annotation annotation, String attributeName) {
659 660 661
		if (annotation == null || !StringUtils.hasLength(attributeName)) {
			return null;
		}
A
Arjen Poutsma 已提交
662
		try {
J
Juergen Hoeller 已提交
663
			Method method = annotation.annotationType().getDeclaredMethod(attributeName);
664
			ReflectionUtils.makeAccessible(method);
A
Arjen Poutsma 已提交
665 666 667 668 669 670 671 672
			return method.invoke(annotation);
		}
		catch (Exception ex) {
			return null;
		}
	}

	/**
673
	 * Retrieve the <em>default value</em> of the {@code &quot;value&quot;} attribute
J
Juergen Hoeller 已提交
674 675
	 * of a single-element Annotation, given an annotation instance.
	 * @param annotation the annotation instance from which to retrieve the default value
676
	 * @return the default value, or {@code null} if not found
A
Arjen Poutsma 已提交
677 678 679 680 681 682 683
	 * @see #getDefaultValue(Annotation, String)
	 */
	public static Object getDefaultValue(Annotation annotation) {
		return getDefaultValue(annotation, VALUE);
	}

	/**
J
Juergen Hoeller 已提交
684
	 * Retrieve the <em>default value</em> of a named attribute, given an annotation instance.
J
Juergen Hoeller 已提交
685
	 * @param annotation the annotation instance from which to retrieve the default value
A
Arjen Poutsma 已提交
686
	 * @param attributeName the name of the attribute value to retrieve
687
	 * @return the default value of the named attribute, or {@code null} if not found
A
Arjen Poutsma 已提交
688 689 690
	 * @see #getDefaultValue(Class, String)
	 */
	public static Object getDefaultValue(Annotation annotation, String attributeName) {
691 692 693
		if (annotation == null) {
			return null;
		}
A
Arjen Poutsma 已提交
694 695 696 697
		return getDefaultValue(annotation.annotationType(), attributeName);
	}

	/**
698
	 * Retrieve the <em>default value</em> of the {@code &quot;value&quot;} attribute
J
Juergen Hoeller 已提交
699 700
	 * of a single-element Annotation, given the {@link Class annotation type}.
	 * @param annotationType the <em>annotation type</em> for which the default value should be retrieved
701
	 * @return the default value, or {@code null} if not found
A
Arjen Poutsma 已提交
702 703 704 705 706 707 708
	 * @see #getDefaultValue(Class, String)
	 */
	public static Object getDefaultValue(Class<? extends Annotation> annotationType) {
		return getDefaultValue(annotationType, VALUE);
	}

	/**
J
Juergen Hoeller 已提交
709 710
	 * Retrieve the <em>default value</em> of a named attribute, given the
	 * {@link Class annotation type}.
J
Juergen Hoeller 已提交
711
	 * @param annotationType the <em>annotation type</em> for which the default value should be retrieved
A
Arjen Poutsma 已提交
712
	 * @param attributeName the name of the attribute value to retrieve.
713
	 * @return the default value of the named attribute, or {@code null} if not found
A
Arjen Poutsma 已提交
714 715 716
	 * @see #getDefaultValue(Annotation, String)
	 */
	public static Object getDefaultValue(Class<? extends Annotation> annotationType, String attributeName) {
717 718 719
		if (annotationType == null || !StringUtils.hasLength(attributeName)) {
			return null;
		}
A
Arjen Poutsma 已提交
720
		try {
J
Juergen Hoeller 已提交
721
			return annotationType.getDeclaredMethod(attributeName).getDefaultValue();
A
Arjen Poutsma 已提交
722 723 724 725 726 727
		}
		catch (Exception ex) {
			return null;
		}
	}

728

729 730 731 732 733 734 735 736 737 738 739 740
	private static void logIntrospectionFailure(AnnotatedElement annotatedElement, Exception ex) {
		Log loggerToUse = logger;
		if (loggerToUse == null) {
			loggerToUse = LogFactory.getLog(AnnotationUtils.class);
			logger = loggerToUse;
		}
		if (loggerToUse.isInfoEnabled()) {
			loggerToUse.info("Failed to introspect annotations on [" + annotatedElement + "]: " + ex);
		}
	}


741
	/**
742
	 * Cache key for the AnnotatedElement cache.
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
	 */
	private static class AnnotationCacheKey {

		private final AnnotatedElement element;

		private final Class<? extends Annotation> annotationType;

		public AnnotationCacheKey(AnnotatedElement element, Class<? extends Annotation> annotationType) {
			this.element = element;
			this.annotationType = annotationType;
		}

		@Override
		public boolean equals(Object other) {
			if (this == other) {
				return true;
			}
			if (!(other instanceof AnnotationCacheKey)) {
				return false;
			}
			AnnotationCacheKey otherKey = (AnnotationCacheKey) other;
			return (this.element.equals(otherKey.element) &&
					ObjectUtils.nullSafeEquals(this.annotationType, otherKey.annotationType));
		}

		@Override
		public int hashCode() {
			return (this.element.hashCode() * 29 + this.annotationType.hashCode());
		}
	}


775 776 777 778 779 780 781 782 783 784
	private static class AnnotationCollector<A extends Annotation> {

		private final Class<? extends Annotation> containerAnnotationType;

		private final Class<A> annotationType;

		private final Set<AnnotatedElement> visited = new HashSet<AnnotatedElement>();

		private final Set<A> result = new LinkedHashSet<A>();

J
Juergen Hoeller 已提交
785
		public AnnotationCollector(Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) {
786 787 788 789 790 791 792 793 794 795 796 797
			this.containerAnnotationType = containerAnnotationType;
			this.annotationType = annotationType;
		}

		public Set<A> getResult(AnnotatedElement element) {
			process(element);
			return Collections.unmodifiableSet(this.result);
		}

		@SuppressWarnings("unchecked")
		private void process(AnnotatedElement annotatedElement) {
			if (this.visited.add(annotatedElement)) {
798 799 800
				for (Annotation ann : annotatedElement.getAnnotations()) {
					if (ObjectUtils.nullSafeEquals(this.annotationType, ann.annotationType())) {
						this.result.add((A) ann);
801
					}
802 803
					else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, ann.annotationType())) {
						this.result.addAll(getValue(ann));
804
					}
805 806
					else if (!isInJavaLangAnnotationPackage(ann)) {
						process(ann.annotationType());
807 808 809 810 811 812
					}
				}
			}
		}

		@SuppressWarnings("unchecked")
813
		private List<A> getValue(Annotation annotation) {
814 815
			try {
				Method method = annotation.annotationType().getDeclaredMethod("value");
816
				ReflectionUtils.makeAccessible(method);
817
				return Arrays.asList((A[]) method.invoke(annotation));
818 819
			}
			catch (Exception ex) {
820 821
				// Unable to read value from repeating annotation container -> ignore it.
				return Collections.emptyList();
822 823 824
			}
		}
	}
J
Juergen Hoeller 已提交
825

A
Arjen Poutsma 已提交
826
}