Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2002-2007 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.springframework.beans;
 
 import java.util.List;
 
Static convenience methods for JavaBeans: for instantiating beans, checking bean property types, copying bean properties, etc.

Mainly for use within the framework, but to some degree also useful for application classes.

Author(s):
Rod Johnson
Juergen Hoeller
Rob Harrop
 
 public abstract class BeanUtils {

Convenience method to instantiate a class using its no-arg constructor. As this method doesn't try to load classes by name, it should avoid class-loading issues.

Note that this method tries to set the constructor accessible if given a non-accessible (that is, non-public) constructor.

Parameters:
clazz class to instantiate
Returns:
the new instance
Throws:
BeanInstantiationException if the bean cannot be instantiated
 
 	public static Object instantiateClass(Class clazzthrows BeanInstantiationException {
 		Assert.notNull(clazz"Class must not be null");
 		if (clazz.isInterface()) {
 			throw new BeanInstantiationException(clazz"Specified class is an interface");
 		}
 		try {
 			return instantiateClass(clazz.getDeclaredConstructor((Class[]) null), null);
 		}
 		catch (NoSuchMethodException ex) {
 			throw new BeanInstantiationException(clazz"No default constructor found"ex);
 		}
 	}

Convenience method to instantiate a class using the given constructor. As this method doesn't try to load classes by name, it should avoid class-loading issues.

Note that this method tries to set the constructor accessible if given a non-accessible (that is, non-public) constructor.

Parameters:
ctor the constructor to instantiate
args the constructor arguments to apply
Returns:
the new instance
Throws:
BeanInstantiationException if the bean cannot be instantiated
 
 	public static Object instantiateClass(Constructor ctorObject[] argsthrows BeanInstantiationException {
 		Assert.notNull(ctor"Constructor must not be null");
 		try {
 			ReflectionUtils.makeAccessible(ctor);
 			return ctor.newInstance(args);
 		}
 		catch (InstantiationException ex) {
 					"Is it an abstract class?"ex);
 		}
 		catch (IllegalAccessException ex) {
 					"Has the class definition changed? Is the constructor accessible?"ex);
 		}
 		catch (IllegalArgumentException ex) {
 					"Illegal arguments for constructor"ex);
 		}
 		catch (InvocationTargetException ex) {
 					"Constructor threw exception"ex.getTargetException());
		}
	}

Find a method with the given method name and the given parameter types, declared on the given class or one of its superclasses. Prefers public methods, but will return a protected, package access, or private method too.

Checks Class.getMethod first, falling back to findDeclaredMethod. This allows to find public methods without issues even in environments with restricted Java security settings.

Parameters:
clazz the class to check
methodName the name of the method to find
paramTypes the parameter types of the method to find
Returns:
the Method object, or null if not found
See also:
java.lang.Class.getMethod(java.lang.String,java.lang.Class[])
findDeclaredMethod(java.lang.Class,java.lang.String,java.lang.Class[])
	public static Method findMethod(Class clazzString methodNameClass[] paramTypes) {
		try {
			return clazz.getMethod(methodNameparamTypes);
		}
		catch (NoSuchMethodException ex) {
			return findDeclaredMethod(clazzmethodNameparamTypes);
		}
	}

Find a method with the given method name and the given parameter types, declared on the given class or one of its superclasses. Will return a public, protected, package access, or private method.

Checks Class.getDeclaredMethod, cascading upwards to all superclasses.

Parameters:
clazz the class to check
methodName the name of the method to find
paramTypes the parameter types of the method to find
Returns:
the Method object, or null if not found
See also:
java.lang.Class.getDeclaredMethod(java.lang.String,java.lang.Class[])
	public static Method findDeclaredMethod(Class clazzString methodNameClass[] paramTypes) {
		try {
			return clazz.getDeclaredMethod(methodNameparamTypes);
		}
		catch (NoSuchMethodException ex) {
			if (clazz.getSuperclass() != null) {
				return findDeclaredMethod(clazz.getSuperclass(), methodNameparamTypes);
			}
			return null;
		}
	}

Find a method with the given method name and minimal parameters (best case: none), declared on the given class or one of its superclasses. Prefers public methods, but will return a protected, package access, or private method too.

Checks Class.getMethods first, falling back to findDeclaredMethodWithMinimalParameters. This allows to find public methods without issues even in environments with restricted Java security settings.

Parameters:
clazz the class to check
methodName the name of the method to find
Returns:
the Method object, or null if not found
Throws:
java.lang.IllegalArgumentException if methods of the given name were found but could not be resolved to a unique method with minimal parameters
See also:
java.lang.Class.getMethods()
findDeclaredMethodWithMinimalParameters(java.lang.Class,java.lang.String)
	public static Method findMethodWithMinimalParameters(Class clazzString methodName)
		Method targetMethod = doFindMethodWithMinimalParameters(clazz.getDeclaredMethods(), methodName);
		if (targetMethod == null) {
			return findDeclaredMethodWithMinimalParameters(clazzmethodName);
		}
		return targetMethod;
	}

Find a method with the given method name and minimal parameters (best case: none), declared on the given class or one of its superclasses. Will return a public, protected, package access, or private method.

Checks Class.getDeclaredMethods, cascading upwards to all superclasses.

Parameters:
clazz the class to check
methodName the name of the method to find
Returns:
the Method object, or null if not found
Throws:
java.lang.IllegalArgumentException if methods of the given name were found but could not be resolved to a unique method with minimal parameters
See also:
java.lang.Class.getDeclaredMethods()
	public static Method findDeclaredMethodWithMinimalParameters(Class clazzString methodName)
		Method targetMethod = doFindMethodWithMinimalParameters(clazz.getDeclaredMethods(), methodName);
		if (targetMethod == null && clazz.getSuperclass() != null) {
		}
		return targetMethod;
	}

Find a method with the given method name and minimal parameters (best case: none) in the given list of methods.

Parameters:
methods the methods to check
methodName the name of the method to find
Returns:
the Method object, or null if not found
Throws:
java.lang.IllegalArgumentException if methods of the given name were found but could not be resolved to a unique method with minimal parameters
	private static Method doFindMethodWithMinimalParameters(Method[] methodsString methodName)
		Method targetMethod = null;
		int numMethodsFoundWithCurrentMinimumArgs = 0;
		for (int i = 0; i < methods.lengthi++) {
			if (methods[i].getName().equals(methodName)) {
				int numParams = methods[i].getParameterTypes().length;
				if (targetMethod == null ||
						numParams < targetMethod.getParameterTypes().length) {
					targetMethod = methods[i];
					numMethodsFoundWithCurrentMinimumArgs = 1;
				}
				else {
					if (targetMethod.getParameterTypes().length == numParams) {
						// Additional candidate with same length.
						numMethodsFoundWithCurrentMinimumArgs++;
					}
				}
			}
		}
		if (numMethodsFoundWithCurrentMinimumArgs > 1) {
			throw new IllegalArgumentException("Cannot resolve method '" + methodName +
					"' to a unique method. Attempted to resolve to overloaded method with " +
					"the least number of parameters, but there were " +
					numMethodsFoundWithCurrentMinimumArgs + " candidates.");
		}
		return targetMethod;
	}

Parse a method signature in the form methodName[([arg_list])], where arg_list is an optional, comma-separated list of fully-qualified type names, and attempts to resolve that signature against the supplied Class.

When not supplying an argument list (methodName) the method whose name matches and has the least number of parameters will be returned. When supplying an argument type list, only the method whose name and argument types match will be returned.

Note then that methodName and methodName() are not resolved in the same way. The signature methodName means the method called methodName with the least number of arguments, whereas methodName() means the method called methodName with exactly 0 arguments.

If no method can be found, then null is returned.

Parameters:
signature the method signature as String representation
clazz the class to resolve the method signature against
Returns:
the resolved Method
See also:
findMethod(java.lang.Class,java.lang.String,java.lang.Class[])
findMethodWithMinimalParameters(java.lang.Class,java.lang.String)
	public static Method resolveSignature(String signatureClass clazz) {
		Assert.hasText(signature"'signature' must not be empty");
		Assert.notNull(clazz"Class must not be null");
		int firstParen = signature.indexOf("(");
		int lastParen = signature.indexOf(")");
		if (firstParen > -1 && lastParen == -1) {
			throw new IllegalArgumentException("Invalid method signature '" + signature +
					"': expected closing ')' for args list");
		}
		else if (lastParen > -1 && firstParen == -1) {
			throw new IllegalArgumentException("Invalid method signature '" + signature +
					"': expected opening '(' for args list");
		}
		else if (firstParen == -1 && lastParen == -1) {
			return findMethodWithMinimalParameters(clazzsignature);
		}
		else {
			String methodName = signature.substring(0, firstParen);
			String[] parameterTypeNames =
					StringUtils.commaDelimitedListToStringArray(signature.substring(firstParen + 1, lastParen));
			Class[] parameterTypes = new Class[parameterTypeNames.length];
			for (int i = 0; i < parameterTypeNames.lengthi++) {
				String parameterTypeName = parameterTypeNames[i].trim();
				try {
					parameterTypes[i] = ClassUtils.forName(parameterTypeNameclazz.getClassLoader());
				}
				catch (Throwable ex) {
					throw new IllegalArgumentException("Invalid method signature: unable to resolve type [" +
							parameterTypeName + "] for argument " + i + ". Root cause: " + ex);
				}
			}
			return findMethod(clazzmethodNameparameterTypes);
		}
	}


Retrieve the JavaBeans PropertyDescriptors of a given class.

Parameters:
clazz the Class to retrieve the PropertyDescriptors for
Returns:
an array of PropertyDescriptors for the given class
Throws:
BeansException if PropertyDescriptor look fails
	public static PropertyDescriptor[] getPropertyDescriptors(Class clazzthrows BeansException {
		CachedIntrospectionResults cr = CachedIntrospectionResults.forClass(clazz);
	}

Retrieve the JavaBeans PropertyDescriptors for the given property.

Parameters:
clazz the Class to retrieve the PropertyDescriptor for
propertyName the name of the property
Returns:
the corresponding PropertyDescriptor, or null if none
Throws:
BeansException if PropertyDescriptor lookup fails
	public static PropertyDescriptor getPropertyDescriptor(Class clazzString propertyName)
			throws BeansException {
		CachedIntrospectionResults cr = CachedIntrospectionResults.forClass(clazz);
		return cr.getPropertyDescriptor(propertyName);
	}

Find a JavaBeans PropertyDescriptor for the given method, with the method either being the read method or the write method for that bean property.

Parameters:
method the method to find a corresponding PropertyDescriptor for
Returns:
the corresponding PropertyDescriptor, or null if none
Throws:
BeansException if PropertyDescriptor lookup fails
	public static PropertyDescriptor findPropertyForMethod(Method methodthrows BeansException {
		Assert.notNull(method"Method must not be null");
		for (int i = 0; i < pds.lengthi++) {
			PropertyDescriptor pd = pds[i];
			if (method.equals(pd.getReadMethod()) || method.equals(pd.getWriteMethod())) {
				return pd;
			}
		}
		return null;
	}

Determine the bean property type for the given property from the given classes/interfaces, if possible.

Parameters:
propertyName the name of the bean property
beanClasses the classes to check against
Returns:
the property type, or Object.class as fallback
	public static Class findPropertyType(String propertyNameClass[] beanClasses) {
		if (beanClasses != null) {
			for (int i = 0; i < beanClasses.lengthi++) {
				PropertyDescriptor pd = getPropertyDescriptor(beanClasses[i], propertyName);
				if (pd != null) {
					return pd.getPropertyType();
				}
			}
		}
		return Object.class;
	}

Check if the given type represents a "simple" property: a primitive, a String, a Class, or a corresponding array.

Used to determine properties to check for a "simple" dependency-check.

	public static boolean isSimpleProperty(Class clazz) {
		Assert.notNull(clazz"Class must not be null");
		return clazz.isPrimitive() || ClassUtils.isPrimitiveArray(clazz) ||
				ClassUtils.isPrimitiveWrapper(clazz) || ClassUtils.isPrimitiveWrapperArray(clazz) ||
				clazz.equals(String.class) || clazz.equals(String[].class) ||
				clazz.equals(Class.class) || clazz.equals(Class[].class);
	}

Determine if the given target type is assignable from the given value type, assuming setting by reflection. Considers primitive wrapper classes as assignable to the corresponding primitive types.

Deprecated:
as of Spring 2.0, in favor of ClassUtils.isAssignable
Parameters:
targetType the target type
valueType the value type that should be assigned to the target type
Returns:
if the target type is assignable from the value type
See also:
org.springframework.util.ClassUtils.isAssignable(java.lang.Class,java.lang.Class)
	public static boolean isAssignable(Class targetTypeClass valueType) {
		return ClassUtils.isAssignable(targetTypevalueType);
	}

Determine if the given type is assignable from the given value, assuming setting by reflection. Considers primitive wrapper classes as assignable to the corresponding primitive types.

Deprecated:
as of Spring 2.0, in favor of ClassUtils.isAssignableValue
Parameters:
type the target type
value the value that should be assigned to the type
Returns:
if the type is assignable from the value
See also:
org.springframework.util.ClassUtils.isAssignableValue(java.lang.Class,java.lang.Object)
	public static boolean isAssignable(Class typeObject value) {
		return ClassUtils.isAssignableValue(typevalue);
	}


Copy the property values of the given source bean into the target bean.

Note: The source and target classes do not have to match or even be derived from each other, as long as the properties match. Any bean properties that the source bean exposes but the target bean does not will silently be ignored.

This is just a convenience method. For more complex transfer needs, consider using a full BeanWrapper.

Parameters:
source the source bean
target the target bean
Throws:
BeansException if the copying failed
See also:
BeanWrapper
	public static void copyProperties(Object sourceObject targetthrows BeansException {
		copyProperties(sourcetargetnullnull);
	}

Copy the property values of the given source bean into the given target bean, only setting properties defined in the given "editable" class (or interface).

Note: The source and target classes do not have to match or even be derived from each other, as long as the properties match. Any bean properties that the source bean exposes but the target bean does not will silently be ignored.

This is just a convenience method. For more complex transfer needs, consider using a full BeanWrapper.

Parameters:
source the source bean
target the target bean
editable the class (or interface) to restrict property setting to
Throws:
BeansException if the copying failed
See also:
BeanWrapper
	public static void copyProperties(Object sourceObject targetClass editable)
			throws BeansException {
		copyProperties(sourcetargeteditablenull);
	}

Copy the property values of the given source bean into the given target bean, ignoring the given "ignoreProperties".

Note: The source and target classes do not have to match or even be derived from each other, as long as the properties match. Any bean properties that the source bean exposes but the target bean does not will silently be ignored.

This is just a convenience method. For more complex transfer needs, consider using a full BeanWrapper.

Parameters:
source the source bean
target the target bean
ignoreProperties array of property names to ignore
Throws:
BeansException if the copying failed
See also:
BeanWrapper
	public static void copyProperties(Object sourceObject targetString[] ignoreProperties)
			throws BeansException {
		copyProperties(sourcetargetnullignoreProperties);
	}

Copy the property values of the given source bean into the given target bean.

Note: The source and target classes do not have to match or even be derived from each other, as long as the properties match. Any bean properties that the source bean exposes but the target bean does not will silently be ignored.

Parameters:
source the source bean
target the target bean
editable the class (or interface) to restrict property setting to
ignoreProperties array of property names to ignore
Throws:
BeansException if the copying failed
See also:
BeanWrapper
	private static void copyProperties(Object sourceObject targetClass editableString[] ignoreProperties)
			throws BeansException {
		Assert.notNull(source"Source must not be null");
		Assert.notNull(target"Target must not be null");
		Class actualEditable = target.getClass();
		if (editable != null) {
			if (!editable.isInstance(target)) {
				throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
						"] not assignable to Editable class [" + editable.getName() + "]");
			}
			actualEditable = editable;
		}
		PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
		List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
		for (int i = 0; i < targetPds.lengthi++) {
			PropertyDescriptor targetPd = targetPds[i];
			if (targetPd.getWriteMethod() != null &&
					(ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
				PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null && sourcePd.getReadMethod() != null) {
					try {
						Method readMethod = sourcePd.getReadMethod();
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(sourcenew Object[0]);
						Method writeMethod = targetPd.getWriteMethod();
						if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
							writeMethod.setAccessible(true);
						}
						writeMethod.invoke(targetnew Object[] {value});
					}
					catch (Throwable ex) {
						throw new FatalBeanException("Could not copy properties from source to target"ex);
					}
				}
			}
		}
	}
New to GrepCode? Check out our FAQ X