Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2002-2005 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;
 import java.util.Map;
 
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 {

Map with primitive wrapper type as key and corresponding primitive type as value, for example: Integer.class -> int.class
 
 	private static final Map primitiveWrapperTypeMap = new HashMap(8);
 	static {
 		.put(Boolean.classboolean.class);
 		.put(Byte.classbyte.class);
 		.put(Character.classchar.class);
 		.put(Short.classshort.class);
 		.put(Integer.classint.class);
 		.put(Long.classlong.class);
 		.put(Float.classfloat.class);
 		.put(Double.classdouble.class);
 	}

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 (i.e. non-public) constructor.

Parameters:
clazz class to instantiate
Returns:
the new instance
 
 	public static Object instantiateClass(Class clazzthrows BeansException {
 		Assert.notNull(clazz"clazz must not be null");
 		if (clazz.isInterface()) {
 			throw new FatalBeanException(
 					"Class [" + clazz.getName() + "] cannot be instantiated: it is an interface");
 		}
 		try {
 			return instantiateClass(clazz.getDeclaredConstructor((Class[]) null), null);
 		}
 		catch (NoSuchMethodException ex) {
 			throw new FatalBeanException("Could not instantiate class [" + clazz.getName() +
 					"]: 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 (i.e. non-public) constructor.

Parameters:
ctor constructor to instantiate
Returns:
the new instance
 
 	public static Object instantiateClass(Constructor ctorObject[] argsthrows BeansException {
 		Assert.notNull(ctor"ctor must not be null");
 		try {
 			if (!Modifier.isPublic(ctor.getModifiers()) ||
 					!Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) {
 				ctor.setAccessible(true);
 			}
			return ctor.newInstance(args);
		}
		catch (InstantiationException ex) {
			throw new FatalBeanException("Could not instantiate class [" + ctor.getDeclaringClass().getName() +
					"]: Is it an abstract class?"ex);
		}
		catch (IllegalAccessException ex) {
			throw new FatalBeanException("Could not instantiate class [" + ctor.getDeclaringClass().getName() +
					"]: Has the class definition changed? Is the constructor accessible?"ex);
		}
			throw new FatalBeanException("Could not instantiate class [" + ctor.getDeclaringClass().getName() +
					"]: illegal args for constructor"ex);
		}
			throw new FatalBeanException("Could not instantiate class [" + ctor.getDeclaringClass().getName() +
					"]; 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
See also:
java.lang.Class.getMethods()
findDeclaredMethodWithMinimalParameters(java.lang.Class,java.lang.String)
	public static Method findMethodWithMinimalParameters(Class clazzString methodName) {
		Method[] methods = clazz.getMethods();
		Method targetMethod = null;
		for (int i = 0; i < methods.lengthi++) {
			if (methods[i].getName().equals(methodName)) {
				if (targetMethod == null ||
						methods[i].getParameterTypes().length < targetMethod.getParameterTypes().length) {
					targetMethod = methods[i];
				}
			}
		}
		if (targetMethod != null) {
			return targetMethod;
		}
		else {
			return findDeclaredMethodWithMinimalParameters(clazzmethodName);
		}
	}

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
See also:
java.lang.Class.getDeclaredMethods()
	public static Method findDeclaredMethodWithMinimalParameters(Class clazzString methodName) {
		Method[] methods = clazz.getDeclaredMethods();
		Method targetMethod = null;
		for (int i = 0; i < methods.lengthi++) {
			if (methods[i].getName().equals(methodName)) {
				if (targetMethod == null ||
						methods[i].getParameterTypes().length < targetMethod.getParameterTypes().length) {
					targetMethod = methods[i];
				}
			}
		}
		if (targetMethod != null) {
			return targetMethod;
		}
		else {
			if (clazz.getSuperclass() != null) {
			}
			return null;
		}
	}

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.

For example used in a bean factory's constructor resolution.

Parameters:
type the target type
value the value that should be assigned to the type
Returns:
if the type is assignable from the value
	public static boolean isAssignable(Class typeObject value) {
		Assert.notNull(type"type must not be null");
		return (value != null ? isAssignable(typevalue.getClass()) : !type.isPrimitive());
	}

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.

For example used in BeanWrapperImpl's custom editor matrching.

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
	public static boolean isAssignable(Class targetTypeClass valueType) {
		Assert.notNull(targetType"targetType must not be null");
		Assert.notNull(valueType"valueType must not be null");
		return (targetType.isAssignableFrom(valueType) ||
				targetType.equals(.get(valueType)));
	}

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

Check if the given class represents an array of primitives, i.e. boolean, byte, char, short, int, long, float, or double.
	public static boolean isPrimitiveArray(Class clazz) {
		return (clazz.isArray() && clazz.getComponentType().isPrimitive());
	}

Check if the given class represents a primitive wrapper, i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double.
	public static boolean isPrimitiveWrapper(Class clazz) {
	}

Check if the given class represents an array of primitive wrappers, i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double.
	public static boolean isPrimitiveWrapperArray(Class clazz) {
		return (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));
	}

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

Parameters:
source source bean
target target bean
Throws:
java.lang.IllegalArgumentException if the classes of source and target do not match
	public static void copyProperties(Object sourceObject target)
		copyProperties(sourcetargetnull);
	}

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

Parameters:
source the source bean
target the target bean
ignoreProperties array of property names to ignore
Throws:
java.lang.IllegalArgumentException if the classes of source and target do not match
	public static void copyProperties(Object sourceObject targetString[] ignoreProperties)
		Assert.notNull(source"source must not be null");
		Assert.notNull(target"source must not be null");
		List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
		BeanWrapper sourceBw = new BeanWrapperImpl(source);
		BeanWrapper targetBw = new BeanWrapperImpl(target);
		for (int i = 0; i < sourceBw.getPropertyDescriptors().lengthi++) {
			PropertyDescriptor sourceDesc = sourceBw.getPropertyDescriptors()[i];
			String name = sourceDesc.getName();
			if (ignoreProperties == null || (!ignoreList.contains(name))) {
				PropertyDescriptor targetDesc = targetBw.getPropertyDescriptor(name);
				if (targetDesc.getWriteMethod() != null && targetDesc.getReadMethod() != null) {
					values.addPropertyValue(new PropertyValue(namesourceBw.getPropertyValue(name)));
				}
			}
		}
		targetBw.setPropertyValues(values);
	}

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

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 look fails
	public static PropertyDescriptor findPropertyForMethod(Method methodthrows BeansException {
		Assert.notNull(method"method must not be null");
		for (int i = 0; i < pds.lengthi++) {
			if (method.equals(pds[i].getReadMethod()) || method.equals(pds[i].getWriteMethod())) {
				return pds[i];
			}
		}
		return null;
	}
New to GrepCode? Check out our FAQ X