ReflectionUtils.java 30.4 KB
Newer Older
1
/*
2
 * Copyright 2002-2016 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
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
28
import java.util.LinkedList;
29
import java.util.List;
30
import java.util.Map;
31 32 33 34

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

48 49 50 51 52 53
	/**
	 * Naming prefix for CGLIB-renamed methods.
	 * @see #isCglibRenamedMethod
	 */
	private static final String CGLIB_RENAMED_METHOD_PREFIX = "CGLIB$";

54 55 56 57
	private static final Method[] NO_METHODS = {};

	private static final Field[] NO_FIELDS = {};

J
Juergen Hoeller 已提交
58

59
	/**
60 61
	 * Cache for {@link Class#getDeclaredMethods()} plus equivalent default methods
	 * from Java 8 based interfaces, allowing for fast iteration.
62
	 */
63
	private static final Map<Class<?>, Method[]> declaredMethodsCache = new ConcurrentReferenceHashMap<>(256);
64

65 66 67
	/**
	 * Cache for {@link Class#getDeclaredFields()}, allowing for fast iteration.
	 */
68
	private static final Map<Class<?>, Field[]> declaredFieldsCache = new ConcurrentReferenceHashMap<>(256);
69

J
Juergen Hoeller 已提交
70

71
	/**
72
	 * Attempt to find a {@link Field field} on the supplied {@link Class} with the
73
	 * supplied {@code name}. Searches all superclasses up to {@link Object}.
74 75
	 * @param clazz the class to introspect
	 * @param name the name of the field
76
	 * @return the corresponding Field object, or {@code null} if not found
77
	 */
78
	public static Field findField(Class<?> clazz, String name) {
79 80 81 82
		return findField(clazz, name, null);
	}

	/**
83
	 * Attempt to find a {@link Field field} on the supplied {@link Class} with the
84
	 * supplied {@code name} and/or {@link Class type}. Searches all superclasses
85
	 * up to {@link Object}.
86
	 * @param clazz the class to introspect
87 88 89
	 * @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
90
	 */
91
	public static Field findField(Class<?> clazz, String name, Class<?> type) {
92 93
		Assert.notNull(clazz, "Class must not be null");
		Assert.isTrue(name != null || type != null, "Either name or type of the field must be specified");
94
		Class<?> searchType = clazz;
95
		while (Object.class != searchType && searchType != null) {
96
			Field[] fields = getDeclaredFields(searchType);
J
Juergen Hoeller 已提交
97
			for (Field field : fields) {
J
Juergen Hoeller 已提交
98 99
				if ((name == null || name.equals(field.getName())) &&
						(type == null || type.equals(field.getType()))) {
100 101 102 103 104 105 106 107 108
					return field;
				}
			}
			searchType = searchType.getSuperclass();
		}
		return null;
	}

	/**
109
	 * Set the field represented by the supplied {@link Field field object} on the
110
	 * specified {@link Object target object} to the specified {@code value}.
111 112 113
	 * 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)}.
114 115
	 * @param field the field to set
	 * @param target the target object on which to set the field
J
Juergen Hoeller 已提交
116
	 * @param value the value to set (may be {@code null})
117 118 119 120 121 122 123
	 */
	public static void setField(Field field, Object target, Object value) {
		try {
			field.set(target, value);
		}
		catch (IllegalAccessException ex) {
			handleReflectionException(ex);
J
Juergen Hoeller 已提交
124 125
			throw new IllegalStateException(
					"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
126 127 128 129
		}
	}

	/**
130 131 132 133 134
	 * 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)}.
135 136 137 138 139 140 141 142 143 144
	 * @param field the field to get
	 * @param target the target object from which to get the field
	 * @return the field's current value
	 */
	public static Object getField(Field field, Object target) {
		try {
			return field.get(target);
		}
		catch (IllegalAccessException ex) {
			handleReflectionException(ex);
145 146
			throw new IllegalStateException(
					"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
147 148 149 150
		}
	}

	/**
151
	 * Attempt to find a {@link Method} on the supplied class with the supplied name
152 153
	 * and no parameters. Searches all superclasses up to {@code Object}.
	 * <p>Returns {@code null} if no {@link Method} can be found.
154 155
	 * @param clazz the class to introspect
	 * @param name the name of the method
156
	 * @return the Method object, or {@code null} if none found
157
	 */
158
	public static Method findMethod(Class<?> clazz, String name) {
P
Phillip Webb 已提交
159
		return findMethod(clazz, name, new Class<?>[0]);
160 161 162
	}

	/**
163
	 * Attempt to find a {@link Method} on the supplied class with the supplied name
164 165
	 * and parameter types. Searches all superclasses up to {@code Object}.
	 * <p>Returns {@code null} if no {@link Method} can be found.
166 167
	 * @param clazz the class to introspect
	 * @param name the name of the method
168
	 * @param paramTypes the parameter types of the method
169 170
	 * (may be {@code null} to indicate any signature)
	 * @return the Method object, or {@code null} if none found
171
	 */
172
	public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
173 174
		Assert.notNull(clazz, "Class must not be null");
		Assert.notNull(name, "Method name must not be null");
175
		Class<?> searchType = clazz;
176
		while (searchType != null) {
177
			Method[] methods = (searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType));
J
Juergen Hoeller 已提交
178
			for (Method method : methods) {
J
Juergen Hoeller 已提交
179 180
				if (name.equals(method.getName()) &&
						(paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
181 182 183 184 185 186 187 188 189
					return method;
				}
			}
			searchType = searchType.getSuperclass();
		}
		return null;
	}

	/**
190
	 * Invoke the specified {@link Method} against the supplied target object with no arguments.
191
	 * The target object can be {@code null} when invoking a static {@link Method}.
192
	 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}.
193 194 195 196 197 198
	 * @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[])
	 */
	public static Object invokeMethod(Method method, Object target) {
199
		return invokeMethod(method, target, new Object[0]);
200 201 202
	}

	/**
203
	 * Invoke the specified {@link Method} against the supplied target object with the
204
	 * supplied arguments. The target object can be {@code null} when invoking a
205 206
	 * static {@link Method}.
	 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}.
207 208
	 * @param method the method to invoke
	 * @param target the target object to invoke the method on
209
	 * @param args the invocation arguments (may be {@code null})
210 211
	 * @return the invocation result, if any
	 */
212
	public static Object invokeMethod(Method method, Object target, Object... args) {
213 214 215 216 217 218 219 220 221 222
		try {
			return method.invoke(target, args);
		}
		catch (Exception ex) {
			handleReflectionException(ex);
		}
		throw new IllegalStateException("Should never get here");
	}

	/**
223 224
	 * Invoke the specified JDBC API {@link Method} against the supplied target
	 * object with no arguments.
225 226 227 228 229 230 231
	 * @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[])
	 */
	public static Object invokeJdbcMethod(Method method, Object target) throws SQLException {
232
		return invokeJdbcMethod(method, target, new Object[0]);
233 234 235
	}

	/**
236 237
	 * Invoke the specified JDBC API {@link Method} against the supplied target
	 * object with the supplied arguments.
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 243 244
	 * @return the invocation result, if any
	 * @throws SQLException the JDBC API SQLException to rethrow (if any)
	 * @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
	 */
245
	public static Object invokeJdbcMethod(Method method, Object target, Object... args) throws SQLException {
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
		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");
	}

	/**
262 263
	 * 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 已提交
264
	 * <p>Throws the underlying RuntimeException or Error in case of an
265
	 * InvocationTargetException with such a root cause. Throws an
266 267
	 * IllegalStateException with an appropriate message or
	 * UndeclaredThrowableException otherwise.
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	 * @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;
		}
283
		throw new UndeclaredThrowableException(ex);
284 285 286
	}

	/**
287 288
	 * 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 已提交
289
	 * <p>Throws the underlying RuntimeException or Error in case of such a root
290
	 * cause. Throws an UndeclaredThrowableException otherwise.
291 292 293 294 295 296 297 298
	 * @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 已提交
299 300 301
	 * <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.
302 303 304
	 * <p>Rethrows the underlying exception cast to a {@link RuntimeException} or
	 * {@link Error} if appropriate; otherwise, throws an
	 * {@link UndeclaredThrowableException}.
305 306 307 308 309 310 311 312 313 314
	 * @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;
		}
315
		throw new UndeclaredThrowableException(ex);
316 317 318 319
	}

	/**
	 * Rethrow the given {@link Throwable exception}, which is presumably the
J
Juergen Hoeller 已提交
320 321 322
	 * <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 已提交
323
	 * <p>Rethrows the underlying exception cast to an {@link Exception} or
324 325
	 * {@link Error} if appropriate; otherwise, throws an
	 * {@link UndeclaredThrowableException}.
326 327 328 329 330 331 332 333 334 335
	 * @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;
		}
336
		throw new UndeclaredThrowableException(ex);
337 338 339
	}

	/**
340
	 * Determine whether the given method explicitly declares the given
J
Juergen Hoeller 已提交
341 342
	 * exception or one of its superclasses, which means that an exception
	 * of that type can be propagated as-is within a reflective invocation.
343 344
	 * @param method the declaring method
	 * @param exceptionType the exception to throw
345 346
	 * @return {@code true} if the exception can be thrown as-is;
	 * {@code false} if it needs to be wrapped
347
	 */
348
	public static boolean declaresException(Method method, Class<?> exceptionType) {
349
		Assert.notNull(method, "Method must not be null");
350 351
		Class<?>[] declaredExceptions = method.getExceptionTypes();
		for (Class<?> declaredException : declaredExceptions) {
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
			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 已提交
370
	 * @see java.lang.Object#equals(Object)
371 372 373 374 375
	 */
	public static boolean isEqualsMethod(Method method) {
		if (method == null || !method.getName().equals("equals")) {
			return false;
		}
376
		Class<?>[] paramTypes = method.getParameterTypes();
377 378 379 380 381
		return (paramTypes.length == 1 && paramTypes[0] == Object.class);
	}

	/**
	 * Determine whether the given method is a "hashCode" method.
J
Juergen Hoeller 已提交
382
	 * @see java.lang.Object#hashCode()
383 384
	 */
	public static boolean isHashCodeMethod(Method method) {
385
		return (method != null && method.getName().equals("hashCode") && method.getParameterCount() == 0);
386 387 388 389 390 391 392
	}

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

396 397 398 399
	/**
	 * Determine whether the given method is originally declared by {@link java.lang.Object}.
	 */
	public static boolean isObjectMethod(Method method) {
J
Juergen Hoeller 已提交
400 401 402
		if (method == null) {
			return false;
		}
403 404 405
		try {
			Object.class.getDeclaredMethod(method.getName(), method.getParameterTypes());
			return true;
J
Juergen Hoeller 已提交
406 407
		}
		catch (Exception ex) {
408 409 410 411
			return false;
		}
	}

412
	/**
J
Juergen Hoeller 已提交
413 414
	 * Determine whether the given method is a CGLIB 'renamed' method,
	 * following the pattern "CGLIB$methodName$0".
415
	 * @param renamedMethod the method to check
416
	 * @see org.springframework.cglib.proxy.Enhancer#rename
417 418
	 */
	public static boolean isCglibRenamedMethod(Method renamedMethod) {
419
		String name = renamedMethod.getName();
420 421 422 423 424 425
		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 已提交
426
						(i < name.length() - 1) && name.charAt(i) == '$');
427 428
		}
		return false;
429 430
	}

431
	/**
432
	 * Make the given field accessible, explicitly setting it accessible if
433
	 * necessary. The {@code setAccessible(true)} method is only called
434 435
	 * when actually necessary, to avoid unnecessary conflicts with a JVM
	 * SecurityManager (if active).
436 437 438 439
	 * @param field the field to make accessible
	 * @see java.lang.reflect.Field#setAccessible
	 */
	public static void makeAccessible(Field field) {
J
Juergen Hoeller 已提交
440 441
		if ((!Modifier.isPublic(field.getModifiers()) ||
				!Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
442
				Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
443 444 445 446 447
			field.setAccessible(true);
		}
	}

	/**
448
	 * Make the given method accessible, explicitly setting it accessible if
449
	 * necessary. The {@code setAccessible(true)} method is only called
450 451
	 * when actually necessary, to avoid unnecessary conflicts with a JVM
	 * SecurityManager (if active).
452 453 454 455
	 * @param method the method to make accessible
	 * @see java.lang.reflect.Method#setAccessible
	 */
	public static void makeAccessible(Method method) {
456 457
		if ((!Modifier.isPublic(method.getModifiers()) ||
				!Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
458 459 460 461 462
			method.setAccessible(true);
		}
	}

	/**
463
	 * Make the given constructor accessible, explicitly setting it accessible
464
	 * if necessary. The {@code setAccessible(true)} method is only called
465 466
	 * when actually necessary, to avoid unnecessary conflicts with a JVM
	 * SecurityManager (if active).
467 468 469
	 * @param ctor the constructor to make accessible
	 * @see java.lang.reflect.Constructor#setAccessible
	 */
470
	public static void makeAccessible(Constructor<?> ctor) {
471 472
		if ((!Modifier.isPublic(ctor.getModifiers()) ||
				!Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
473 474 475 476
			ctor.setAccessible(true);
		}
	}

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
	/**
	 * 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;
	}

493 494 495 496 497 498 499
	/**
	 * 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
	 * @since 4.2
500
	 * @throws IllegalStateException if introspection fails
501 502 503 504 505 506 507 508 509 510 511 512 513 514
	 * @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);
			}
		}
	}

515
	/**
516 517
	 * Perform the given callback operation on all matching methods of the given
	 * class and superclasses.
J
Juergen Hoeller 已提交
518
	 * <p>The same named method occurring on subclass and superclass will appear
519
	 * twice, unless excluded by a {@link MethodFilter}.
520
	 * @param clazz the class to introspect
521
	 * @param mc the callback to invoke for each method
522
	 * @throws IllegalStateException if introspection fails
523 524
	 * @see #doWithMethods(Class, MethodCallback, MethodFilter)
	 */
525
	public static void doWithMethods(Class<?> clazz, MethodCallback mc) {
526
		doWithMethods(clazz, mc, null);
527 528 529
	}

	/**
530
	 * Perform the given callback operation on all matching methods of the given
531
	 * class and superclasses (or given interface and super-interfaces).
J
Juergen Hoeller 已提交
532
	 * <p>The same named method occurring on subclass and superclass will appear
533
	 * twice, unless excluded by the specified {@link MethodFilter}.
534
	 * @param clazz the class to introspect
535 536
	 * @param mc the callback to invoke for each method
	 * @param mf the filter that determines the methods to apply the callback to
537
	 * @throws IllegalStateException if introspection fails
538
	 */
539
	public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) {
540
		// Keep backing up the inheritance hierarchy.
541
		Method[] methods = getDeclaredMethods(clazz);
542 543 544 545 546 547 548 549
		for (Method method : methods) {
			if (mf != null && !mf.matches(method)) {
				continue;
			}
			try {
				mc.doWith(method);
			}
			catch (IllegalAccessException ex) {
550
				throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + ex);
551 552 553 554 555 556 557 558
			}
		}
		if (clazz.getSuperclass() != null) {
			doWithMethods(clazz.getSuperclass(), mc, mf);
		}
		else if (clazz.isInterface()) {
			for (Class<?> superIfc : clazz.getInterfaces()) {
				doWithMethods(superIfc, mc, mf);
559
			}
560
		}
561 562 563
	}

	/**
564 565 566
	 * Get all declared methods on the leaf class and all superclasses.
	 * Leaf class methods are included first.
	 * @param leafClass the class to introspect
567
	 * @throws IllegalStateException if introspection fails
568
	 */
569
	public static Method[] getAllDeclaredMethods(Class<?> leafClass) {
570
		final List<Method> methods = new ArrayList<>(32);
571
		doWithMethods(leafClass, new MethodCallback() {
572
			@Override
573
			public void doWith(Method method) {
J
Juergen Hoeller 已提交
574
				methods.add(method);
575 576
			}
		});
J
Juergen Hoeller 已提交
577
		return methods.toArray(new Method[methods.size()]);
578 579
	}

580
	/**
581 582 583 584
	 * 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
585
	 * @throws IllegalStateException if introspection fails
586
	 */
587
	public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) {
588
		final List<Method> methods = new ArrayList<>(32);
589
		doWithMethods(leafClass, new MethodCallback() {
590
			@Override
591 592 593 594 595 596
			public void doWith(Method method) {
				boolean knownSignature = false;
				Method methodBeingOverriddenWithCovariantReturnType = null;
				for (Method existingMethod : methods) {
					if (method.getName().equals(existingMethod.getName()) &&
							Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {
J
Juergen Hoeller 已提交
597
						// Is this a covariant return type situation?
598 599 600
						if (existingMethod.getReturnType() != method.getReturnType() &&
								existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {
							methodBeingOverriddenWithCovariantReturnType = existingMethod;
J
Juergen Hoeller 已提交
601 602
						}
						else {
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
							knownSignature = true;
						}
						break;
					}
				}
				if (methodBeingOverriddenWithCovariantReturnType != null) {
					methods.remove(methodBeingOverriddenWithCovariantReturnType);
				}
				if (!knownSignature && !isCglibRenamedMethod(method)) {
					methods.add(method);
				}
			}
		});
		return methods.toArray(new Method[methods.size()]);
	}

619
	/**
620
	 * This variant retrieves {@link Class#getDeclaredMethods()} from a local cache
621
	 * in order to avoid the JVM's SecurityManager check and defensive array copying.
622 623 624 625
	 * 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
626
	 * @throws IllegalStateException if introspection fails
627
	 * @see Class#getDeclaredMethods()
628 629
	 */
	private static Method[] getDeclaredMethods(Class<?> clazz) {
630
		Assert.notNull(clazz, "Class must not be null");
631 632
		Method[] result = declaredMethodsCache.get(clazz);
		if (result == null) {
633 634 635 636 637 638 639 640 641 642 643 644 645 646
			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;
647
				}
648
				declaredMethodsCache.put(clazz, (result.length == 0 ? NO_METHODS : result));
649
			}
650 651 652
			catch (Throwable ex) {
				throw new IllegalStateException("Failed to introspect Class [" + clazz +
						"] from ClassLoader [" + clazz.getClassLoader() + "]", ex);
653
			}
654 655 656 657
		}
		return result;
	}

658 659 660 661 662 663
	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) {
664
						result = new LinkedList<>();
665 666 667 668 669 670 671 672
					}
					result.add(ifcMethod);
				}
			}
		}
		return result;
	}

673
	/**
674 675
	 * Invoke the given callback on all fields in the target class, going up the
	 * class hierarchy to get all declared fields.
676
	 * @param clazz the target class to analyze
677
	 * @param fc the callback to invoke for each field
678
	 * @since 4.2
679
	 * @throws IllegalStateException if introspection fails
680
	 * @see #doWithFields
681
	 */
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
	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
698
	 * @throws IllegalStateException if introspection fails
699 700
	 */
	public static void doWithFields(Class<?> clazz, FieldCallback fc) {
701
		doWithFields(clazz, fc, null);
702 703 704
	}

	/**
705 706
	 * Invoke the given callback on all fields in the target class, going up the
	 * class hierarchy to get all declared fields.
707
	 * @param clazz the target class to analyze
708 709
	 * @param fc the callback to invoke for each field
	 * @param ff the filter that determines the fields to apply the callback to
710
	 * @throws IllegalStateException if introspection fails
711
	 */
712
	public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff) {
713
		// Keep backing up the inheritance hierarchy.
714
		Class<?> targetClass = clazz;
715
		do {
716
			Field[] fields = getDeclaredFields(targetClass);
J
Juergen Hoeller 已提交
717 718
			for (Field field : fields) {
				if (ff != null && !ff.matches(field)) {
719 720 721
					continue;
				}
				try {
J
Juergen Hoeller 已提交
722
					fc.doWith(field);
723 724
				}
				catch (IllegalAccessException ex) {
725
					throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex);
726 727 728
				}
			}
			targetClass = targetClass.getSuperclass();
729 730
		}
		while (targetClass != null && targetClass != Object.class);
731 732
	}

733 734 735 736 737
	/**
	 * 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
738
	 * @throws IllegalStateException if introspection fails
739 740 741
	 * @see Class#getDeclaredFields()
	 */
	private static Field[] getDeclaredFields(Class<?> clazz) {
742
		Assert.notNull(clazz, "Class must not be null");
743 744
		Field[] result = declaredFieldsCache.get(clazz);
		if (result == null) {
745 746 747 748 749 750 751 752
			try {
				result = clazz.getDeclaredFields();
				declaredFieldsCache.put(clazz, (result.length == 0 ? NO_FIELDS : result));
			}
			catch (Throwable ex) {
				throw new IllegalStateException("Failed to introspect Class [" + clazz +
						"] from ClassLoader [" + clazz.getClassLoader() + "]", ex);
			}
753 754 755 756
		}
		return result;
	}

757 758 759 760
	/**
	 * 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.
761
	 * @throws IllegalStateException if introspection fails
762
	 */
763
	public static void shallowCopyFieldState(final Object src, final Object dest) {
764 765 766 767 768 769 770
		if (src == null) {
			throw new IllegalArgumentException("Source for field copy cannot be null");
		}
		if (dest == null) {
			throw new IllegalArgumentException("Destination for field copy cannot be null");
		}
		if (!src.getClass().isAssignableFrom(dest.getClass())) {
J
Juergen Hoeller 已提交
771 772
			throw new IllegalArgumentException("Destination class [" + dest.getClass().getName() +
					"] must be same or subclass as source class [" + src.getClass().getName() + "]");
773 774
		}
		doWithFields(src.getClass(), new FieldCallback() {
775
			@Override
776 777 778 779 780 781 782 783
			public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
				makeAccessible(field);
				Object srcValue = field.get(src);
				field.set(dest, srcValue);
			}
		}, COPYABLE_FIELDS);
	}

784 785 786 787 788 789 790 791 792
	/**
	 * Clear the internal method/field cache.
	 * @since 4.2.4
	 */
	public static void clearCache() {
		declaredMethodsCache.clear();
		declaredFieldsCache.clear();
	}

793 794 795 796

	/**
	 * Action to take on each method.
	 */
797
	@FunctionalInterface
798
	public interface MethodCallback {
799 800 801 802 803 804 805 806

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

J
Juergen Hoeller 已提交
807

808
	/**
S
Sam Brannen 已提交
809
	 * Callback optionally used to filter methods to be operated on by a method callback.
810
	 */
811
	@FunctionalInterface
812
	public interface MethodFilter {
813 814 815 816 817 818 819 820

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

821

822 823 824
	/**
	 * Callback interface invoked on each field in the hierarchy.
	 */
825
	@FunctionalInterface
826
	public interface FieldCallback {
827 828 829 830 831 832 833 834

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

J
Juergen Hoeller 已提交
835

836
	/**
J
Juergen Hoeller 已提交
837
	 * Callback optionally used to filter fields to be operated on by a field callback.
838
	 */
839
	@FunctionalInterface
840
	public interface FieldFilter {
841 842 843 844 845 846 847 848 849 850 851 852

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


	/**
	 * Pre-built FieldFilter that matches all non-static, non-final fields.
	 */
853
	public static final FieldFilter COPYABLE_FIELDS = new FieldFilter() {
854

855
		@Override
856
		public boolean matches(Field field) {
857
			return !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
858 859 860
		}
	};

861

862 863 864
	/**
	 * Pre-built MethodFilter that matches all non-bridge methods.
	 */
865
	public static final MethodFilter NON_BRIDGED_METHODS = new MethodFilter() {
866

867
		@Override
868 869 870 871 872
		public boolean matches(Method method) {
			return !method.isBridge();
		}
	};

873 874 875

	/**
	 * Pre-built MethodFilter that matches all non-bridge methods
876
	 * which are not declared on {@code java.lang.Object}.
877
	 */
878
	public static final MethodFilter USER_DECLARED_METHODS = new MethodFilter() {
879

880
		@Override
881 882 883 884 885
		public boolean matches(Method method) {
			return (!method.isBridge() && method.getDeclaringClass() != Object.class);
		}
	};

886
}