AnnotationUtils.java 27.1 KB
Newer Older
A
Arjen Poutsma 已提交
1
/*
S
Sam Brannen 已提交
2
 * Copyright 2002-2013 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;
29
import java.util.WeakHashMap;
A
Arjen Poutsma 已提交
30 31 32

import org.springframework.core.BridgeMethodResolver;
import org.springframework.util.Assert;
33
import org.springframework.util.ObjectUtils;
34
import org.springframework.util.ReflectionUtils;
A
Arjen Poutsma 已提交
35 36

/**
S
Sam Brannen 已提交
37 38 39 40
 * 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 已提交
41
 *
S
Sam Brannen 已提交
42 43 44 45 46 47 48 49
 * <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 已提交
50 51 52 53 54
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @author Mark Fisher
C
Chris Beams 已提交
55
 * @author Chris Beams
56
 * @author Phillip Webb
A
Arjen Poutsma 已提交
57 58 59 60 61 62 63
 * @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 */
J
Juergen Hoeller 已提交
64
	static final String VALUE = "value";
A
Arjen Poutsma 已提交
65

66
	private static final Map<Class<?>, Boolean> annotatedInterfaceCache = new WeakHashMap<Class<?>, Boolean>();
67

J
Juergen Hoeller 已提交
68

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
	/**
	 * 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
	 * @param annotationType the annotation class to look for, both locally and as a meta-annotation
	 * @return the matching annotation or {@code null} if not found
	 * @since 4.0
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Annotation> T getAnnotation(Annotation ann, Class<T> annotationType) {
		if (annotationType.isInstance(ann)) {
			return (T) ann;
		}
		return ann.annotationType().getAnnotation(annotationType);
	}

85
	/**
C
Chris Beams 已提交
86 87 88 89 90 91 92
	 * 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 ae the Method, Constructor or Field from which to get the annotation
	 * @param annotationType the annotation class to look for, both locally and as a meta-annotation
	 * @return the matching annotation or {@code null} if not found
	 * @since 3.1
93 94 95 96 97 98 99 100 101 102 103 104 105 106
	 */
	public static <T extends Annotation> T getAnnotation(AnnotatedElement ae, Class<T> annotationType) {
		T ann = ae.getAnnotation(annotationType);
		if (ann == null) {
			for (Annotation metaAnn : ae.getAnnotations()) {
				ann = metaAnn.annotationType().getAnnotation(annotationType);
				if (ann != null) {
					break;
				}
			}
		}
		return ann;
	}

A
Arjen Poutsma 已提交
107 108 109 110 111 112 113 114 115 116 117 118
	/**
	 * Get all {@link Annotation Annotations} from the supplied {@link Method}.
	 * <p>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();
	}

	/**
119
	 * Get a single {@link Annotation} of {@code annotationType} from the supplied {@link Method}.
A
Arjen Poutsma 已提交
120 121 122 123 124 125 126
	 * <p>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 extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {
127
		Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
128
		return getAnnotation((AnnotatedElement) resolvedMethod, annotationType);
A
Arjen Poutsma 已提交
129 130
	}

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
	/**
	 * 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
	 * @param annotationType the annotation class to look for
	 * @return the annotations found
	 * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
	 * @since 4.0
	 */
	public static <A extends Annotation> Set<A> getRepeatableAnnotation(Method method,
			Class<? extends Annotation> containerAnnotationType, Class<A> 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.
	 * <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
	 * @param annotationType the annotation class to look for
	 * @return the annotations found
	 * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
	 * @since 4.0
	 */
	public static <A extends Annotation> Set<A> getRepeatableAnnotation(AnnotatedElement annotatedElement,
			Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) {
		if (annotatedElement.getAnnotations().length == 0) {
			return Collections.emptySet();
		}
		return new AnnotationCollector<A>(containerAnnotationType, annotationType).getResult(annotatedElement);
	}

A
Arjen Poutsma 已提交
170
	/**
S
Sam Brannen 已提交
171 172 173 174 175
	 * 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.
	 * <p>Annotations on methods are not inherited by default, so we need to handle
	 * this explicitly.
A
Arjen Poutsma 已提交
176 177
	 * @param method the method to look for annotations on
	 * @param annotationType the annotation class to look for
178
	 * @return the annotation found, or {@code null} if none found
A
Arjen Poutsma 已提交
179 180 181
	 */
	public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) {
		A annotation = getAnnotation(method, annotationType);
182
		Class<?> clazz = method.getDeclaringClass();
J
Juergen Hoeller 已提交
183
		if (annotation == null) {
184
			annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
185
		}
A
Arjen Poutsma 已提交
186
		while (annotation == null) {
187 188
			clazz = clazz.getSuperclass();
			if (clazz == null || clazz.equals(Object.class)) {
A
Arjen Poutsma 已提交
189 190 191
				break;
			}
			try {
192
				Method equivalentMethod = clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
A
Arjen Poutsma 已提交
193 194 195
				annotation = getAnnotation(equivalentMethod, annotationType);
			}
			catch (NoSuchMethodException ex) {
196 197 198
				// No equivalent method found
			}
			if (annotation == null) {
199
				annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
A
Arjen Poutsma 已提交
200 201 202 203 204
			}
		}
		return annotation;
	}

205
	private static <A extends Annotation> A searchOnInterfaces(Method method, Class<A> annotationType, Class<?>[] ifcs) {
206
		A annotation = null;
J
Juergen Hoeller 已提交
207
		for (Class<?> iface : ifcs) {
208 209 210 211 212 213 214 215 216 217 218
			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;
				}
219
			}
220 221 222 223 224 225 226 227 228
		}
		return annotation;
	}

	private static boolean isInterfaceWithAnnotatedMethods(Class<?> iface) {
		synchronized (annotatedInterfaceCache) {
			Boolean flag = annotatedInterfaceCache.get(iface);
			if (flag != null) {
				return flag;
229
			}
230 231 232 233 234 235
			boolean found = false;
			for (Method ifcMethod : iface.getMethods()) {
				if (ifcMethod.getAnnotations().length > 0) {
					found = true;
					break;
				}
236
			}
237 238
			annotatedInterfaceCache.put(iface, found);
			return found;
239 240 241
		}
	}

A
Arjen Poutsma 已提交
242
	/**
S
Sam Brannen 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
	 * 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.
	 * <p>This method explicitly handles class-level annotations which are not
	 * declared as {@link java.lang.annotation.Inherited inherited} <i>as well
	 * as meta-annotations and annotations on interfaces</i>.
	 * <p>The algorithm operates as follows:
	 * <ol>
	 * <li>Search for an annotation on the given class and return it if found.
	 * <li>Recursively search through all interfaces that the given class
	 * declares, returning the annotation from the first matching candidate, if any.
	 * <li>Recursively search through all annotations that the given class
	 * declares, returning the annotation from the first matching candidate, if any.
	 * <li>Proceed with introspection of the superclass hierarchy of the given
	 * class by returning to step #1 with the superclass as the class to look for
	 * annotations on.
	 * </ol>
A
Arjen Poutsma 已提交
260 261
	 * @param clazz the class to look for annotations on
	 * @param annotationType the annotation class to look for
262
	 * @return the annotation found, or {@code null} if none found
A
Arjen Poutsma 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275
	 */
	public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> 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;
			}
		}
276 277 278 279 280 281 282 283
		if (!Annotation.class.isAssignableFrom(clazz)) {
			for (Annotation ann : clazz.getAnnotations()) {
				annotation = findAnnotation(ann.annotationType(), annotationType);
				if (annotation != null) {
					return annotation;
				}
			}
		}
284
		Class<?> superClass = clazz.getSuperclass();
285
		if (superClass == null || superClass.equals(Object.class)) {
A
Arjen Poutsma 已提交
286 287 288 289 290 291
			return null;
		}
		return findAnnotation(superClass, annotationType);
	}

	/**
292 293 294 295 296
	 * 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 已提交
297 298 299 300
	 * 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.
301 302
	 * @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}
303 304
	 * @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 已提交
305
	 * if not found
A
Arjen Poutsma 已提交
306 307
	 * @see Class#isAnnotationPresent(Class)
	 * @see Class#getDeclaredAnnotations()
308 309
	 * @see #findAnnotationDeclaringClassForTypes(List, Class)
	 * @see #isAnnotationDeclaredLocally(Class, Class)
A
Arjen Poutsma 已提交
310 311 312 313 314 315
	 */
	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;
		}
316 317 318 319
		if (isAnnotationDeclaredLocally(annotationType, clazz)) {
			return clazz;
		}
		return findAnnotationDeclaringClass(annotationType, clazz.getSuperclass());
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
	}

	/**
	 * 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
342
	 * @since 3.2.2
343 344 345 346 347
	 * @see Class#isAnnotationPresent(Class)
	 * @see Class#getDeclaredAnnotations()
	 * @see #findAnnotationDeclaringClass(Class, Class)
	 * @see #isAnnotationDeclaredLocally(Class, Class)
	 */
348
	public static Class<?> findAnnotationDeclaringClassForTypes(List<Class<? extends Annotation>> annotationTypes, Class<?> clazz) {
349 350 351 352 353 354 355 356 357 358
		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 已提交
359 360 361
	}

	/**
362 363
	 * Determine whether an annotation for the specified {@code annotationType} is
	 * declared locally on the supplied {@code clazz}. The supplied {@link Class}
J
Juergen Hoeller 已提交
364 365
	 * may represent any type.
	 * <p>Note: This method does <strong>not</strong> determine if the annotation is
S
Sam Brannen 已提交
366 367 368
	 * {@linkplain java.lang.annotation.Inherited inherited}. For greater clarity
	 * regarding inherited annotations, consider using
	 * {@link #isAnnotationInherited(Class, Class)} instead.
A
Arjen Poutsma 已提交
369
	 * @param annotationType the Class object corresponding to the annotation type
J
Juergen Hoeller 已提交
370
	 * @param clazz the Class object corresponding to the class on which to check for the annotation
371 372
	 * @return {@code true} if an annotation for the specified {@code annotationType}
	 * is declared locally on the supplied {@code clazz}
A
Arjen Poutsma 已提交
373 374 375 376 377 378 379
	 * @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;
S
Sam Brannen 已提交
380
		for (Annotation annotation : clazz.getDeclaredAnnotations()) {
A
Arjen Poutsma 已提交
381 382 383 384 385 386 387 388 389
			if (annotation.annotationType().equals(annotationType)) {
				declaredLocally = true;
				break;
			}
		}
		return declaredLocally;
	}

	/**
390
	 * Determine whether an annotation for the specified {@code annotationType} is present
S
Sam Brannen 已提交
391 392
	 * on the supplied {@code clazz} and is {@linkplain java.lang.annotation.Inherited inherited}
	 * (i.e., not declared locally for the class).
393
	 * <p>If the supplied {@code clazz} is an interface, only the interface itself will be checked.
J
Juergen Hoeller 已提交
394
	 * In accordance with standard meta-annotation semantics, the inheritance hierarchy for interfaces
S
Sam Brannen 已提交
395 396
	 * 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 已提交
397
	 * @param annotationType the Class object corresponding to the annotation type
J
Juergen Hoeller 已提交
398
	 * @param clazz the Class object corresponding to the class on which to check for the annotation
399
	 * @return {@code true} if an annotation for the specified {@code annotationType} is present
S
Sam Brannen 已提交
400
	 * on the supplied {@code clazz} and is <em>inherited</em>
A
Arjen Poutsma 已提交
401 402 403 404 405 406 407 408 409 410
	 * @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));
	}

	/**
411 412 413 414 415
	 * Retrieve the given annotation's attributes as a Map, preserving all attribute types
	 * as-is.
	 * <p>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.
A
Arjen Poutsma 已提交
416
	 * @param annotation the annotation to retrieve the attributes for
J
Juergen Hoeller 已提交
417 418
	 * @return the Map of annotation attributes, with attribute names as keys and
	 * corresponding attribute values as values
A
Arjen Poutsma 已提交
419 420
	 */
	public static Map<String, Object> getAnnotationAttributes(Annotation annotation) {
421
		return getAnnotationAttributes(annotation, false, false);
422 423 424
	}

	/**
425 426 427 428 429 430
	 * Retrieve the given annotation's attributes as a Map. Equivalent to calling
	 * {@link #getAnnotationAttributes(Annotation, boolean, boolean)} with
	 * the {@code nestedAnnotationsAsMap} parameter set to {@code false}.
	 * <p>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.
431
	 * @param annotation the annotation to retrieve the attributes for
432 433 434
	 * @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
J
Juergen Hoeller 已提交
435 436
	 * @return the Map of annotation attributes, with attribute names as keys and
	 * corresponding attribute values as values
437
	 */
438
	public static Map<String, Object> getAnnotationAttributes(Annotation annotation, boolean classValuesAsString) {
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
		return getAnnotationAttributes(annotation, classValuesAsString, false);
	}

	/**
	 * Retrieve the given annotation's attributes as an {@link AnnotationAttributes}
	 * map structure. Implemented in Spring 3.1.1 to provide fully recursive annotation
	 * reading capabilities on par with that of the reflection-based
	 * {@link org.springframework.core.type.StandardAnnotationMetadata}.
	 * @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
	 * @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
	 */
459 460
	public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, boolean classValuesAsString,
			boolean nestedAnnotationsAsMap) {
461 462

		AnnotationAttributes attrs = new AnnotationAttributes();
A
Arjen Poutsma 已提交
463
		Method[] methods = annotation.annotationType().getDeclaredMethods();
464
		for (Method method : methods) {
A
Arjen Poutsma 已提交
465 466
			if (method.getParameterTypes().length == 0 && method.getReturnType() != void.class) {
				try {
467
					Object value = method.invoke(annotation);
468
					if (classValuesAsString) {
469
						if (value instanceof Class) {
470
							value = ((Class<?>) value).getName();
471 472
						}
						else if (value instanceof Class[]) {
473
							Class<?>[] clazzArray = (Class[]) value;
474 475 476 477 478 479 480
							String[] newValue = new String[clazzArray.length];
							for (int i = 0; i < clazzArray.length; i++) {
								newValue[i] = clazzArray[i].getName();
							}
							value = newValue;
						}
					}
481
					if (nestedAnnotationsAsMap && value instanceof Annotation) {
482 483
						attrs.put(method.getName(),
							getAnnotationAttributes((Annotation) value, classValuesAsString, nestedAnnotationsAsMap));
484 485
					}
					else if (nestedAnnotationsAsMap && value instanceof Annotation[]) {
486
						Annotation[] realAnnotations = (Annotation[]) value;
487 488
						AnnotationAttributes[] mappedAnnotations = new AnnotationAttributes[realAnnotations.length];
						for (int i = 0; i < realAnnotations.length; i++) {
489 490
							mappedAnnotations[i] = getAnnotationAttributes(
									realAnnotations[i], classValuesAsString, nestedAnnotationsAsMap);
491 492 493 494 495 496
						}
						attrs.put(method.getName(), mappedAnnotations);
					}
					else {
						attrs.put(method.getName(), value);
					}
A
Arjen Poutsma 已提交
497 498 499 500 501 502 503 504 505 506
				}
				catch (Exception ex) {
					throw new IllegalStateException("Could not obtain annotation attribute values", ex);
				}
			}
		}
		return attrs;
	}

	/**
507
	 * Retrieve the <em>value</em> of the {@code &quot;value&quot;} attribute of a
J
Juergen Hoeller 已提交
508
	 * single-element Annotation, given an annotation instance.
A
Arjen Poutsma 已提交
509
	 * @param annotation the annotation instance from which to retrieve the value
510
	 * @return the attribute value, or {@code null} if not found
A
Arjen Poutsma 已提交
511 512 513 514 515 516 517
	 * @see #getValue(Annotation, String)
	 */
	public static Object getValue(Annotation annotation) {
		return getValue(annotation, VALUE);
	}

	/**
J
Juergen Hoeller 已提交
518
	 * Retrieve the <em>value</em> of a named Annotation attribute, given an annotation instance.
A
Arjen Poutsma 已提交
519 520
	 * @param annotation the annotation instance from which to retrieve the value
	 * @param attributeName the name of the attribute value to retrieve
521
	 * @return the attribute value, or {@code null} if not found
J
Juergen Hoeller 已提交
522
	 * @see #getValue(Annotation)
A
Arjen Poutsma 已提交
523 524 525
	 */
	public static Object getValue(Annotation annotation, String attributeName) {
		try {
P
Phillip Webb 已提交
526
			Method method = annotation.annotationType().getDeclaredMethod(attributeName, new Class<?>[0]);
527
			ReflectionUtils.makeAccessible(method);
A
Arjen Poutsma 已提交
528 529 530 531 532 533 534 535
			return method.invoke(annotation);
		}
		catch (Exception ex) {
			return null;
		}
	}

	/**
536
	 * Retrieve the <em>default value</em> of the {@code &quot;value&quot;} attribute
J
Juergen Hoeller 已提交
537 538
	 * of a single-element Annotation, given an annotation instance.
	 * @param annotation the annotation instance from which to retrieve the default value
539
	 * @return the default value, or {@code null} if not found
A
Arjen Poutsma 已提交
540 541 542 543 544 545 546
	 * @see #getDefaultValue(Annotation, String)
	 */
	public static Object getDefaultValue(Annotation annotation) {
		return getDefaultValue(annotation, VALUE);
	}

	/**
J
Juergen Hoeller 已提交
547 548
	 * Retrieve the <em>default value</em> of a named Annotation attribute, given an annotation instance.
	 * @param annotation the annotation instance from which to retrieve the default value
A
Arjen Poutsma 已提交
549
	 * @param attributeName the name of the attribute value to retrieve
550
	 * @return the default value of the named attribute, or {@code null} if not found
A
Arjen Poutsma 已提交
551 552 553 554 555 556 557
	 * @see #getDefaultValue(Class, String)
	 */
	public static Object getDefaultValue(Annotation annotation, String attributeName) {
		return getDefaultValue(annotation.annotationType(), attributeName);
	}

	/**
558
	 * Retrieve the <em>default value</em> of the {@code &quot;value&quot;} attribute
J
Juergen Hoeller 已提交
559 560
	 * 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
561
	 * @return the default value, or {@code null} if not found
A
Arjen Poutsma 已提交
562 563 564 565 566 567 568
	 * @see #getDefaultValue(Class, String)
	 */
	public static Object getDefaultValue(Class<? extends Annotation> annotationType) {
		return getDefaultValue(annotationType, VALUE);
	}

	/**
J
Juergen Hoeller 已提交
569 570
	 * Retrieve the <em>default value</em> of a named Annotation attribute, given the {@link Class annotation type}.
	 * @param annotationType the <em>annotation type</em> for which the default value should be retrieved
A
Arjen Poutsma 已提交
571
	 * @param attributeName the name of the attribute value to retrieve.
572
	 * @return the default value of the named attribute, or {@code null} if not found
A
Arjen Poutsma 已提交
573 574 575 576
	 * @see #getDefaultValue(Annotation, String)
	 */
	public static Object getDefaultValue(Class<? extends Annotation> annotationType, String attributeName) {
		try {
P
Phillip Webb 已提交
577
			Method method = annotationType.getDeclaredMethod(attributeName, new Class<?>[0]);
A
Arjen Poutsma 已提交
578 579 580 581 582 583 584
			return method.getDefaultValue();
		}
		catch (Exception ex) {
			return null;
		}
	}

585 586 587 588 589 590 591 592 593 594 595 596 597 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

	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>();


		public AnnotationCollector(Class<? extends Annotation> containerAnnotationType,
				Class<A> annotationType) {
			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)) {
				for (Annotation annotation : annotatedElement.getAnnotations()) {
					if (ObjectUtils.nullSafeEquals(this.annotationType, annotation.annotationType())) {
						this.result.add((A) annotation);
					}
					else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, annotation.annotationType())) {
						result.addAll(Arrays.asList(getValue(annotation)));
					}
					else {
						process(annotation.annotationType());
					}
				}
			}
		}

		@SuppressWarnings("unchecked")
		private A[] getValue(Annotation annotation) {
			try {
				Method method = annotation.annotationType().getDeclaredMethod("value");
630
				ReflectionUtils.makeAccessible(method);
631 632 633 634 635 636 637 638 639
				return (A[]) method.invoke(annotation);
			}
			catch (Exception ex) {
				throw new IllegalStateException("Unable to read value from repeating annotation container "
								+ this.containerAnnotationType.getName(), ex);
			}
		}

	}
A
Arjen Poutsma 已提交
640
}