ReflectionUtils.java 30.5 KB
Newer Older
1
/*
2
 * Copyright 2002-2018 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
24
import java.lang.reflect.UndeclaredThrowableException;
25 26 27 28
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
29
import java.util.Map;
30

31 32
import org.springframework.lang.Nullable;

33 34 35
/**
 * Simple utility class for working with the reflection API and handling
 * reflection exceptions.
J
Juergen Hoeller 已提交
36 37 38
 *
 * <p>Only intended for internal use.
 *
39 40 41 42 43
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Rod Johnson
 * @author Costin Leau
 * @author Sam Brannen
44
 * @author Chris Beams
45 46 47 48
 * @since 1.2.2
 */
public abstract class ReflectionUtils {

49
	/**
50 51 52
	 * Pre-built MethodFilter that matches all non-bridge methods.
	 * @since 3.0
	 * @deprecated as of 5.0.11, in favor of a custom {@link MethodFilter}
53
	 */
54 55 56
	@Deprecated
	public static final MethodFilter NON_BRIDGED_METHODS =
			(method -> !method.isBridge());
57

58 59 60 61 62 63 64
	/**
	 * Pre-built MethodFilter that matches all non-bridge non-synthetic methods
	 * which are not declared on {@code java.lang.Object}.
	 * @since 3.0.5
	 */
	public static final MethodFilter USER_DECLARED_METHODS =
			(method -> (!method.isBridge() && !method.isSynthetic() && method.getDeclaringClass() != Object.class));
65

P
Phillip Webb 已提交
66 67 68 69 70 71 72 73
	/**
	 * Pre-built FieldFilter that matches all non-static, non-final fields.
	 */
	public static final FieldFilter COPYABLE_FIELDS =
			field -> !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));


	/**
74 75
	 * Naming prefix for CGLIB-renamed methods.
	 * @see #isCglibRenamedMethod
P
Phillip Webb 已提交
76
	 */
77
	private static final String CGLIB_RENAMED_METHOD_PREFIX = "CGLIB$";
P
Phillip Webb 已提交
78

79
	private static final Method[] NO_METHODS = {};
P
Phillip Webb 已提交
80

81
	private static final Field[] NO_FIELDS = {};
P
Phillip Webb 已提交
82

J
Juergen Hoeller 已提交
83

84
	/**
85 86
	 * Cache for {@link Class#getDeclaredMethods()} plus equivalent default methods
	 * from Java 8 based interfaces, allowing for fast iteration.
87
	 */
88
	private static final Map<Class<?>, Method[]> declaredMethodsCache = new ConcurrentReferenceHashMap<>(256);
89

90 91 92
	/**
	 * Cache for {@link Class#getDeclaredFields()}, allowing for fast iteration.
	 */
93
	private static final Map<Class<?>, Field[]> declaredFieldsCache = new ConcurrentReferenceHashMap<>(256);
94

J
Juergen Hoeller 已提交
95

96
	/**
97
	 * Attempt to find a {@link Field field} on the supplied {@link Class} with the
98
	 * supplied {@code name}. Searches all superclasses up to {@link Object}.
99 100
	 * @param clazz the class to introspect
	 * @param name the name of the field
101
	 * @return the corresponding Field object, or {@code null} if not found
102
	 */
103
	@Nullable
104
	public static Field findField(Class<?> clazz, String name) {
105 106 107 108
		return findField(clazz, name, null);
	}

	/**
109
	 * Attempt to find a {@link Field field} on the supplied {@link Class} with the
110
	 * supplied {@code name} and/or {@link Class type}. Searches all superclasses
111
	 * up to {@link Object}.
112
	 * @param clazz the class to introspect
113 114 115
	 * @param name the name of the field (may be {@code null} if type is specified)
	 * @param type the type of the field (may be {@code null} if name is specified)
	 * @return the corresponding Field object, or {@code null} if not found
116
	 */
117 118
	@Nullable
	public static Field findField(Class<?> clazz, @Nullable String name, @Nullable Class<?> type) {
119 120
		Assert.notNull(clazz, "Class must not be null");
		Assert.isTrue(name != null || type != null, "Either name or type of the field must be specified");
121
		Class<?> searchType = clazz;
122
		while (Object.class != searchType && searchType != null) {
123
			Field[] fields = getDeclaredFields(searchType);
J
Juergen Hoeller 已提交
124
			for (Field field : fields) {
J
Juergen Hoeller 已提交
125 126
				if ((name == null || name.equals(field.getName())) &&
						(type == null || type.equals(field.getType()))) {
127 128 129 130 131 132 133 134 135
					return field;
				}
			}
			searchType = searchType.getSuperclass();
		}
		return null;
	}

	/**
136
	 * Set the field represented by the supplied {@link Field field object} on the
137
	 * specified {@link Object target object} to the specified {@code value}.
138 139 140
	 * In accordance with {@link Field#set(Object, Object)} semantics, the new value
	 * is automatically unwrapped if the underlying field has a primitive type.
	 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}.
141 142
	 * @param field the field to set
	 * @param target the target object on which to set the field
J
Juergen Hoeller 已提交
143
	 * @param value the value to set (may be {@code null})
144
	 */
145
	public static void setField(Field field, @Nullable Object target, @Nullable Object value) {
146 147 148 149 150
		try {
			field.set(target, value);
		}
		catch (IllegalAccessException ex) {
			handleReflectionException(ex);
J
Juergen Hoeller 已提交
151 152
			throw new IllegalStateException(
					"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
153 154 155 156
		}
	}

	/**
157 158 159 160 161
	 * Get the field represented by the supplied {@link Field field object} on the
	 * specified {@link Object target object}. In accordance with {@link Field#get(Object)}
	 * semantics, the returned value is automatically wrapped if the underlying field
	 * has a primitive type.
	 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}.
162 163 164 165
	 * @param field the field to get
	 * @param target the target object from which to get the field
	 * @return the field's current value
	 */
166 167
	@Nullable
	public static Object getField(Field field, @Nullable Object target) {
168 169 170 171 172
		try {
			return field.get(target);
		}
		catch (IllegalAccessException ex) {
			handleReflectionException(ex);
173 174
			throw new IllegalStateException(
					"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
175 176 177 178
		}
	}

	/**
179
	 * Attempt to find a {@link Method} on the supplied class with the supplied name
180 181
	 * and no parameters. Searches all superclasses up to {@code Object}.
	 * <p>Returns {@code null} if no {@link Method} can be found.
182 183
	 * @param clazz the class to introspect
	 * @param name the name of the method
184
	 * @return the Method object, or {@code null} if none found
185
	 */
186
	@Nullable
187
	public static Method findMethod(Class<?> clazz, String name) {
P
Phillip Webb 已提交
188
		return findMethod(clazz, name, new Class<?>[0]);
189 190 191
	}

	/**
192
	 * Attempt to find a {@link Method} on the supplied class with the supplied name
193 194
	 * and parameter types. Searches all superclasses up to {@code Object}.
	 * <p>Returns {@code null} if no {@link Method} can be found.
195 196
	 * @param clazz the class to introspect
	 * @param name the name of the method
197
	 * @param paramTypes the parameter types of the method
198 199
	 * (may be {@code null} to indicate any signature)
	 * @return the Method object, or {@code null} if none found
200
	 */
201 202
	@Nullable
	public static Method findMethod(Class<?> clazz, String name, @Nullable Class<?>... paramTypes) {
203 204
		Assert.notNull(clazz, "Class must not be null");
		Assert.notNull(name, "Method name must not be null");
205
		Class<?> searchType = clazz;
206
		while (searchType != null) {
207
			Method[] methods = (searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType));
J
Juergen Hoeller 已提交
208
			for (Method method : methods) {
J
Juergen Hoeller 已提交
209 210
				if (name.equals(method.getName()) &&
						(paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
211 212 213 214 215 216 217 218 219
					return method;
				}
			}
			searchType = searchType.getSuperclass();
		}
		return null;
	}

	/**
220
	 * Invoke the specified {@link Method} against the supplied target object with no arguments.
221
	 * The target object can be {@code null} when invoking a static {@link Method}.
222
	 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}.
223 224 225 226 227
	 * @param method the method to invoke
	 * @param target the target object to invoke the method on
	 * @return the invocation result, if any
	 * @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
	 */
228 229
	@Nullable
	public static Object invokeMethod(Method method, @Nullable Object target) {
230
		return invokeMethod(method, target, new Object[0]);
231 232 233
	}

	/**
234
	 * Invoke the specified {@link Method} against the supplied target object with the
235
	 * supplied arguments. The target object can be {@code null} when invoking a
236 237
	 * static {@link Method}.
	 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}.
238 239
	 * @param method the method to invoke
	 * @param target the target object to invoke the method on
240
	 * @param args the invocation arguments (may be {@code null})
241 242
	 * @return the invocation result, if any
	 */
243 244
	@Nullable
	public static Object invokeMethod(Method method, @Nullable Object target, @Nullable Object... args) {
245 246 247 248 249 250 251 252 253 254
		try {
			return method.invoke(target, args);
		}
		catch (Exception ex) {
			handleReflectionException(ex);
		}
		throw new IllegalStateException("Should never get here");
	}

	/**
255 256
	 * Invoke the specified JDBC API {@link Method} against the supplied target
	 * object with no arguments.
257 258 259 260 261
	 * @param method the method to invoke
	 * @param target the target object to invoke the method on
	 * @return the invocation result, if any
	 * @throws SQLException the JDBC API SQLException to rethrow (if any)
	 * @see #invokeJdbcMethod(java.lang.reflect.Method, Object, Object[])
262
	 * @deprecated as of 5.0.11, in favor of custom SQLException handling
263
	 */
264
	@Deprecated
265
	@Nullable
266
	public static Object invokeJdbcMethod(Method method, @Nullable Object target) throws SQLException {
267
		return invokeJdbcMethod(method, target, new Object[0]);
268 269 270
	}

	/**
271 272
	 * Invoke the specified JDBC API {@link Method} against the supplied target
	 * object with the supplied arguments.
273 274
	 * @param method the method to invoke
	 * @param target the target object to invoke the method on
275
	 * @param args the invocation arguments (may be {@code null})
276 277 278
	 * @return the invocation result, if any
	 * @throws SQLException the JDBC API SQLException to rethrow (if any)
	 * @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
279
	 * @deprecated as of 5.0.11, in favor of custom SQLException handling
280
	 */
281
	@Deprecated
282
	@Nullable
283 284
	public static Object invokeJdbcMethod(Method method, @Nullable Object target, @Nullable Object... args)
			throws SQLException {
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
		try {
			return method.invoke(target, args);
		}
		catch (IllegalAccessException ex) {
			handleReflectionException(ex);
		}
		catch (InvocationTargetException ex) {
			if (ex.getTargetException() instanceof SQLException) {
				throw (SQLException) ex.getTargetException();
			}
			handleInvocationTargetException(ex);
		}
		throw new IllegalStateException("Should never get here");
	}

	/**
301 302
	 * Handle the given reflection exception. Should only be called if no
	 * checked exception is expected to be thrown by the target method.
J
Juergen Hoeller 已提交
303
	 * <p>Throws the underlying RuntimeException or Error in case of an
304
	 * InvocationTargetException with such a root cause. Throws an
305 306
	 * IllegalStateException with an appropriate message or
	 * UndeclaredThrowableException otherwise.
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
	 * @param ex the reflection exception to handle
	 */
	public static void handleReflectionException(Exception ex) {
		if (ex instanceof NoSuchMethodException) {
			throw new IllegalStateException("Method not found: " + ex.getMessage());
		}
		if (ex instanceof IllegalAccessException) {
			throw new IllegalStateException("Could not access method: " + ex.getMessage());
		}
		if (ex instanceof InvocationTargetException) {
			handleInvocationTargetException((InvocationTargetException) ex);
		}
		if (ex instanceof RuntimeException) {
			throw (RuntimeException) ex;
		}
322
		throw new UndeclaredThrowableException(ex);
323 324 325
	}

	/**
326 327
	 * Handle the given invocation target exception. Should only be called if no
	 * checked exception is expected to be thrown by the target method.
J
Juergen Hoeller 已提交
328
	 * <p>Throws the underlying RuntimeException or Error in case of such a root
329
	 * cause. Throws an UndeclaredThrowableException otherwise.
330 331 332 333 334 335 336 337
	 * @param ex the invocation target exception to handle
	 */
	public static void handleInvocationTargetException(InvocationTargetException ex) {
		rethrowRuntimeException(ex.getTargetException());
	}

	/**
	 * Rethrow the given {@link Throwable exception}, which is presumably the
J
Juergen Hoeller 已提交
338 339 340
	 * <em>target exception</em> of an {@link InvocationTargetException}.
	 * Should only be called if no checked exception is expected to be thrown
	 * by the target method.
341 342 343
	 * <p>Rethrows the underlying exception cast to a {@link RuntimeException} or
	 * {@link Error} if appropriate; otherwise, throws an
	 * {@link UndeclaredThrowableException}.
344 345 346 347 348 349 350 351 352 353
	 * @param ex the exception to rethrow
	 * @throws RuntimeException the rethrown exception
	 */
	public static void rethrowRuntimeException(Throwable ex) {
		if (ex instanceof RuntimeException) {
			throw (RuntimeException) ex;
		}
		if (ex instanceof Error) {
			throw (Error) ex;
		}
354
		throw new UndeclaredThrowableException(ex);
355 356 357 358
	}

	/**
	 * Rethrow the given {@link Throwable exception}, which is presumably the
J
Juergen Hoeller 已提交
359 360 361
	 * <em>target exception</em> of an {@link InvocationTargetException}.
	 * Should only be called if no checked exception is expected to be thrown
	 * by the target method.
J
Juergen Hoeller 已提交
362
	 * <p>Rethrows the underlying exception cast to an {@link Exception} or
363 364
	 * {@link Error} if appropriate; otherwise, throws an
	 * {@link UndeclaredThrowableException}.
365 366 367 368 369 370 371 372 373 374
	 * @param ex the exception to rethrow
	 * @throws Exception the rethrown exception (in case of a checked exception)
	 */
	public static void rethrowException(Throwable ex) throws Exception {
		if (ex instanceof Exception) {
			throw (Exception) ex;
		}
		if (ex instanceof Error) {
			throw (Error) ex;
		}
375
		throw new UndeclaredThrowableException(ex);
376 377 378
	}

	/**
379
	 * Determine whether the given method explicitly declares the given
J
Juergen Hoeller 已提交
380 381
	 * exception or one of its superclasses, which means that an exception
	 * of that type can be propagated as-is within a reflective invocation.
382 383
	 * @param method the declaring method
	 * @param exceptionType the exception to throw
384 385
	 * @return {@code true} if the exception can be thrown as-is;
	 * {@code false} if it needs to be wrapped
386
	 */
387
	public static boolean declaresException(Method method, Class<?> exceptionType) {
388
		Assert.notNull(method, "Method must not be null");
389 390
		Class<?>[] declaredExceptions = method.getExceptionTypes();
		for (Class<?> declaredException : declaredExceptions) {
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
			if (declaredException.isAssignableFrom(exceptionType)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Determine whether the given field is a "public static final" constant.
	 * @param field the field to check
	 */
	public static boolean isPublicStaticFinal(Field field) {
		int modifiers = field.getModifiers();
		return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
	}

	/**
	 * Determine whether the given method is an "equals" method.
J
Juergen Hoeller 已提交
409
	 * @see java.lang.Object#equals(Object)
410
	 */
411
	public static boolean isEqualsMethod(@Nullable Method method) {
412 413 414
		if (method == null || !method.getName().equals("equals")) {
			return false;
		}
415
		Class<?>[] paramTypes = method.getParameterTypes();
416 417 418 419 420
		return (paramTypes.length == 1 && paramTypes[0] == Object.class);
	}

	/**
	 * Determine whether the given method is a "hashCode" method.
J
Juergen Hoeller 已提交
421
	 * @see java.lang.Object#hashCode()
422
	 */
423
	public static boolean isHashCodeMethod(@Nullable Method method) {
424
		return (method != null && method.getName().equals("hashCode") && method.getParameterCount() == 0);
425 426 427 428 429 430
	}

	/**
	 * Determine whether the given method is a "toString" method.
	 * @see java.lang.Object#toString()
	 */
431
	public static boolean isToStringMethod(@Nullable Method method) {
432
		return (method != null && method.getName().equals("toString") && method.getParameterCount() == 0);
433 434
	}

435 436 437
	/**
	 * Determine whether the given method is originally declared by {@link java.lang.Object}.
	 */
438
	public static boolean isObjectMethod(@Nullable Method method) {
J
Juergen Hoeller 已提交
439 440 441
		if (method == null) {
			return false;
		}
442 443 444
		try {
			Object.class.getDeclaredMethod(method.getName(), method.getParameterTypes());
			return true;
J
Juergen Hoeller 已提交
445 446
		}
		catch (Exception ex) {
447 448 449 450
			return false;
		}
	}

451
	/**
J
Juergen Hoeller 已提交
452 453
	 * Determine whether the given method is a CGLIB 'renamed' method,
	 * following the pattern "CGLIB$methodName$0".
454
	 * @param renamedMethod the method to check
455
	 * @see org.springframework.cglib.proxy.Enhancer#rename
456 457
	 */
	public static boolean isCglibRenamedMethod(Method renamedMethod) {
458
		String name = renamedMethod.getName();
459 460 461 462 463 464
		if (name.startsWith(CGLIB_RENAMED_METHOD_PREFIX)) {
			int i = name.length() - 1;
			while (i >= 0 && Character.isDigit(name.charAt(i))) {
				i--;
			}
			return ((i > CGLIB_RENAMED_METHOD_PREFIX.length()) &&
J
Juergen Hoeller 已提交
465
						(i < name.length() - 1) && name.charAt(i) == '$');
466 467
		}
		return false;
468 469
	}

470
	/**
471
	 * Make the given field accessible, explicitly setting it accessible if
472
	 * necessary. The {@code setAccessible(true)} method is only called
473 474
	 * when actually necessary, to avoid unnecessary conflicts with a JVM
	 * SecurityManager (if active).
475 476 477
	 * @param field the field to make accessible
	 * @see java.lang.reflect.Field#setAccessible
	 */
478
	@SuppressWarnings("deprecation")  // on JDK 9
479
	public static void makeAccessible(Field field) {
J
Juergen Hoeller 已提交
480 481
		if ((!Modifier.isPublic(field.getModifiers()) ||
				!Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
482
				Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
483 484 485 486 487
			field.setAccessible(true);
		}
	}

	/**
488
	 * Make the given method accessible, explicitly setting it accessible if
489
	 * necessary. The {@code setAccessible(true)} method is only called
490 491
	 * when actually necessary, to avoid unnecessary conflicts with a JVM
	 * SecurityManager (if active).
492 493 494
	 * @param method the method to make accessible
	 * @see java.lang.reflect.Method#setAccessible
	 */
495
	@SuppressWarnings("deprecation")  // on JDK 9
496
	public static void makeAccessible(Method method) {
497 498
		if ((!Modifier.isPublic(method.getModifiers()) ||
				!Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
499 500 501 502 503
			method.setAccessible(true);
		}
	}

	/**
504
	 * Make the given constructor accessible, explicitly setting it accessible
505
	 * if necessary. The {@code setAccessible(true)} method is only called
506 507
	 * when actually necessary, to avoid unnecessary conflicts with a JVM
	 * SecurityManager (if active).
508 509 510
	 * @param ctor the constructor to make accessible
	 * @see java.lang.reflect.Constructor#setAccessible
	 */
511
	@SuppressWarnings("deprecation")  // on JDK 9
512
	public static void makeAccessible(Constructor<?> ctor) {
513 514
		if ((!Modifier.isPublic(ctor.getModifiers()) ||
				!Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
515 516 517 518
			ctor.setAccessible(true);
		}
	}

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
	/**
	 * Obtain an accessible constructor for the given class and parameters.
	 * @param clazz the clazz to check
	 * @param parameterTypes the parameter types of the desired constructor
	 * @return the constructor reference
	 * @throws NoSuchMethodException if no such constructor exists
	 * @since 5.0
	 */
	public static <T> Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
			throws NoSuchMethodException {

		Constructor<T> ctor = clazz.getDeclaredConstructor(parameterTypes);
		makeAccessible(ctor);
		return ctor;
	}

535 536 537 538 539 540
	/**
	 * Perform the given callback operation on all matching methods of the given
	 * class, as locally declared or equivalent thereof (such as default methods
	 * on Java 8 based interfaces that the given class implements).
	 * @param clazz the class to introspect
	 * @param mc the callback to invoke for each method
541
	 * @throws IllegalStateException if introspection fails
P
Phillip Webb 已提交
542
	 * @since 4.2
543 544 545 546 547 548 549 550 551 552 553 554 555 556
	 * @see #doWithMethods
	 */
	public static void doWithLocalMethods(Class<?> clazz, MethodCallback mc) {
		Method[] methods = getDeclaredMethods(clazz);
		for (Method method : methods) {
			try {
				mc.doWith(method);
			}
			catch (IllegalAccessException ex) {
				throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + ex);
			}
		}
	}

557
	/**
558 559
	 * Perform the given callback operation on all matching methods of the given
	 * class and superclasses.
J
Juergen Hoeller 已提交
560
	 * <p>The same named method occurring on subclass and superclass will appear
561
	 * twice, unless excluded by a {@link MethodFilter}.
562
	 * @param clazz the class to introspect
563
	 * @param mc the callback to invoke for each method
564
	 * @throws IllegalStateException if introspection fails
565 566
	 * @see #doWithMethods(Class, MethodCallback, MethodFilter)
	 */
567
	public static void doWithMethods(Class<?> clazz, MethodCallback mc) {
568
		doWithMethods(clazz, mc, null);
569 570 571
	}

	/**
572
	 * Perform the given callback operation on all matching methods of the given
573
	 * class and superclasses (or given interface and super-interfaces).
J
Juergen Hoeller 已提交
574
	 * <p>The same named method occurring on subclass and superclass will appear
575
	 * twice, unless excluded by the specified {@link MethodFilter}.
576
	 * @param clazz the class to introspect
577 578
	 * @param mc the callback to invoke for each method
	 * @param mf the filter that determines the methods to apply the callback to
579
	 * @throws IllegalStateException if introspection fails
580
	 */
581
	public static void doWithMethods(Class<?> clazz, MethodCallback mc, @Nullable MethodFilter mf) {
582
		// Keep backing up the inheritance hierarchy.
583
		Method[] methods = getDeclaredMethods(clazz);
584 585 586 587 588 589 590 591
		for (Method method : methods) {
			if (mf != null && !mf.matches(method)) {
				continue;
			}
			try {
				mc.doWith(method);
			}
			catch (IllegalAccessException ex) {
592
				throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + ex);
593 594 595 596 597 598 599 600
			}
		}
		if (clazz.getSuperclass() != null) {
			doWithMethods(clazz.getSuperclass(), mc, mf);
		}
		else if (clazz.isInterface()) {
			for (Class<?> superIfc : clazz.getInterfaces()) {
				doWithMethods(superIfc, mc, mf);
601
			}
602
		}
603 604 605
	}

	/**
606 607 608
	 * Get all declared methods on the leaf class and all superclasses.
	 * Leaf class methods are included first.
	 * @param leafClass the class to introspect
609
	 * @throws IllegalStateException if introspection fails
610
	 */
611
	public static Method[] getAllDeclaredMethods(Class<?> leafClass) {
612
		final List<Method> methods = new ArrayList<>(32);
613
		doWithMethods(leafClass, methods::add);
614
		return methods.toArray(new Method[0]);
615 616
	}

617
	/**
618 619 620 621
	 * Get the unique set of declared methods on the leaf class and all superclasses.
	 * Leaf class methods are included first and while traversing the superclass hierarchy
	 * any methods found with signatures matching a method already included are filtered out.
	 * @param leafClass the class to introspect
622
	 * @throws IllegalStateException if introspection fails
623
	 */
624
	public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) {
625
		final List<Method> methods = new ArrayList<>(32);
626 627 628 629 630 631 632 633 634 635
		doWithMethods(leafClass, method -> {
			boolean knownSignature = false;
			Method methodBeingOverriddenWithCovariantReturnType = null;
			for (Method existingMethod : methods) {
				if (method.getName().equals(existingMethod.getName()) &&
						Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {
					// Is this a covariant return type situation?
					if (existingMethod.getReturnType() != method.getReturnType() &&
							existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {
						methodBeingOverriddenWithCovariantReturnType = existingMethod;
636
					}
637 638 639 640
					else {
						knownSignature = true;
					}
					break;
641 642
				}
			}
643 644 645 646 647 648
			if (methodBeingOverriddenWithCovariantReturnType != null) {
				methods.remove(methodBeingOverriddenWithCovariantReturnType);
			}
			if (!knownSignature && !isCglibRenamedMethod(method)) {
				methods.add(method);
			}
649
		});
650
		return methods.toArray(new Method[0]);
651 652
	}

653
	/**
654
	 * This variant retrieves {@link Class#getDeclaredMethods()} from a local cache
655
	 * in order to avoid the JVM's SecurityManager check and defensive array copying.
656 657 658 659
	 * In addition, it also includes Java 8 default methods from locally implemented
	 * interfaces, since those are effectively to be treated just like declared methods.
	 * @param clazz the class to introspect
	 * @return the cached array of methods
660
	 * @throws IllegalStateException if introspection fails
661
	 * @see Class#getDeclaredMethods()
662 663
	 */
	private static Method[] getDeclaredMethods(Class<?> clazz) {
664
		Assert.notNull(clazz, "Class must not be null");
665 666
		Method[] result = declaredMethodsCache.get(clazz);
		if (result == null) {
667 668 669 670 671 672 673 674 675 676 677 678 679 680
			try {
				Method[] declaredMethods = clazz.getDeclaredMethods();
				List<Method> defaultMethods = findConcreteMethodsOnInterfaces(clazz);
				if (defaultMethods != null) {
					result = new Method[declaredMethods.length + defaultMethods.size()];
					System.arraycopy(declaredMethods, 0, result, 0, declaredMethods.length);
					int index = declaredMethods.length;
					for (Method defaultMethod : defaultMethods) {
						result[index] = defaultMethod;
						index++;
					}
				}
				else {
					result = declaredMethods;
681
				}
682
				declaredMethodsCache.put(clazz, (result.length == 0 ? NO_METHODS : result));
683
			}
684
			catch (Throwable ex) {
685
				throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() +
686
						"] from ClassLoader [" + clazz.getClassLoader() + "]", ex);
687
			}
688 689 690 691
		}
		return result;
	}

692
	@Nullable
693 694 695 696 697 698
	private static List<Method> findConcreteMethodsOnInterfaces(Class<?> clazz) {
		List<Method> result = null;
		for (Class<?> ifc : clazz.getInterfaces()) {
			for (Method ifcMethod : ifc.getMethods()) {
				if (!Modifier.isAbstract(ifcMethod.getModifiers())) {
					if (result == null) {
S
stsypanov 已提交
699
						result = new ArrayList<>();
700 701 702 703 704 705 706 707
					}
					result.add(ifcMethod);
				}
			}
		}
		return result;
	}

708
	/**
709
	 * Invoke the given callback on all locally declared fields in the given class.
710
	 * @param clazz the target class to analyze
711
	 * @param fc the callback to invoke for each field
712
	 * @throws IllegalStateException if introspection fails
P
Phillip Webb 已提交
713
	 * @since 4.2
714
	 * @see #doWithFields
715
	 */
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
	public static void doWithLocalFields(Class<?> clazz, FieldCallback fc) {
		for (Field field : getDeclaredFields(clazz)) {
			try {
				fc.doWith(field);
			}
			catch (IllegalAccessException ex) {
				throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex);
			}
		}
	}

	/**
	 * Invoke the given callback on all fields in the target class, going up the
	 * class hierarchy to get all declared fields.
	 * @param clazz the target class to analyze
	 * @param fc the callback to invoke for each field
732
	 * @throws IllegalStateException if introspection fails
733 734
	 */
	public static void doWithFields(Class<?> clazz, FieldCallback fc) {
735
		doWithFields(clazz, fc, null);
736 737 738
	}

	/**
739 740
	 * Invoke the given callback on all fields in the target class, going up the
	 * class hierarchy to get all declared fields.
741
	 * @param clazz the target class to analyze
742 743
	 * @param fc the callback to invoke for each field
	 * @param ff the filter that determines the fields to apply the callback to
744
	 * @throws IllegalStateException if introspection fails
745
	 */
746
	public static void doWithFields(Class<?> clazz, FieldCallback fc, @Nullable FieldFilter ff) {
747
		// Keep backing up the inheritance hierarchy.
748
		Class<?> targetClass = clazz;
749
		do {
750
			Field[] fields = getDeclaredFields(targetClass);
J
Juergen Hoeller 已提交
751 752
			for (Field field : fields) {
				if (ff != null && !ff.matches(field)) {
753 754 755
					continue;
				}
				try {
J
Juergen Hoeller 已提交
756
					fc.doWith(field);
757 758
				}
				catch (IllegalAccessException ex) {
759
					throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex);
760 761 762
				}
			}
			targetClass = targetClass.getSuperclass();
763 764
		}
		while (targetClass != null && targetClass != Object.class);
765 766
	}

767 768 769 770 771
	/**
	 * This variant retrieves {@link Class#getDeclaredFields()} from a local cache
	 * in order to avoid the JVM's SecurityManager check and defensive array copying.
	 * @param clazz the class to introspect
	 * @return the cached array of fields
772
	 * @throws IllegalStateException if introspection fails
773 774 775
	 * @see Class#getDeclaredFields()
	 */
	private static Field[] getDeclaredFields(Class<?> clazz) {
776
		Assert.notNull(clazz, "Class must not be null");
777 778
		Field[] result = declaredFieldsCache.get(clazz);
		if (result == null) {
779 780 781 782 783
			try {
				result = clazz.getDeclaredFields();
				declaredFieldsCache.put(clazz, (result.length == 0 ? NO_FIELDS : result));
			}
			catch (Throwable ex) {
784
				throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() +
785 786
						"] from ClassLoader [" + clazz.getClassLoader() + "]", ex);
			}
787 788 789 790
		}
		return result;
	}

791 792 793 794
	/**
	 * Given the source object and the destination, which must be the same class
	 * or a subclass, copy all fields, including inherited fields. Designed to
	 * work on objects with public no-arg constructors.
795
	 * @throws IllegalStateException if introspection fails
796
	 */
797
	public static void shallowCopyFieldState(final Object src, final Object dest) {
798 799
		Assert.notNull(src, "Source for field copy cannot be null");
		Assert.notNull(dest, "Destination for field copy cannot be null");
800
		if (!src.getClass().isAssignableFrom(dest.getClass())) {
J
Juergen Hoeller 已提交
801 802
			throw new IllegalArgumentException("Destination class [" + dest.getClass().getName() +
					"] must be same or subclass as source class [" + src.getClass().getName() + "]");
803
		}
804 805 806 807
		doWithFields(src.getClass(), field -> {
			makeAccessible(field);
			Object srcValue = field.get(src);
			field.set(dest, srcValue);
808 809 810
		}, COPYABLE_FIELDS);
	}

811 812 813 814 815 816 817 818 819
	/**
	 * Clear the internal method/field cache.
	 * @since 4.2.4
	 */
	public static void clearCache() {
		declaredMethodsCache.clear();
		declaredFieldsCache.clear();
	}

820 821 822 823

	/**
	 * Action to take on each method.
	 */
824
	@FunctionalInterface
825
	public interface MethodCallback {
826 827 828 829 830 831 832 833

		/**
		 * Perform an operation using the given method.
		 * @param method the method to operate on
		 */
		void doWith(Method method) throws IllegalArgumentException, IllegalAccessException;
	}

J
Juergen Hoeller 已提交
834

835
	/**
S
Sam Brannen 已提交
836
	 * Callback optionally used to filter methods to be operated on by a method callback.
837
	 */
838
	@FunctionalInterface
839
	public interface MethodFilter {
840 841 842 843 844 845 846 847

		/**
		 * Determine whether the given method matches.
		 * @param method the method to check
		 */
		boolean matches(Method method);
	}

848

849 850 851
	/**
	 * Callback interface invoked on each field in the hierarchy.
	 */
852
	@FunctionalInterface
853
	public interface FieldCallback {
854 855 856 857 858 859 860 861

		/**
		 * Perform an operation using the given field.
		 * @param field the field to operate on
		 */
		void doWith(Field field) throws IllegalArgumentException, IllegalAccessException;
	}

J
Juergen Hoeller 已提交
862

863
	/**
J
Juergen Hoeller 已提交
864
	 * Callback optionally used to filter fields to be operated on by a field callback.
865
	 */
866
	@FunctionalInterface
867
	public interface FieldFilter {
868 869 870 871 872 873 874 875 876

		/**
		 * Determine whether the given field matches.
		 * @param field the field to check
		 */
		boolean matches(Field field);
	}

}