📄 beanutils.java
字号:
/**
*文件功能:
*/
package com.common.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
/**
* @作者 徐建协
* @日期 2008-1-18
*/
public class BeanUtils {
protected static final Log logger = LogFactory.getLog(BeanUtils.class);
private BeanUtils() {
}
/**
* 循环向上转型,获取对象的DeclaredField.
*
* @throws NoSuchFieldException 如果没有该Field时抛出.
*/
public static Field getDeclaredField(Object object, String propertyName) throws NoSuchFieldException {
Assert.notNull(object);
Assert.hasText(propertyName);
return getDeclaredField(object.getClass(), propertyName);
}
/**
* 循环向上转型,获取对象的DeclaredField.
*
* @throws NoSuchFieldException 如果没有该Field时抛出.
*/
public static Field getDeclaredField(Class clazz, String propertyName) throws NoSuchFieldException {
Assert.notNull(clazz);
Assert.hasText(propertyName);
for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
return superClass.getDeclaredField(propertyName);
} catch (NoSuchFieldException e) {
// Field不在当前类定义,继续向上转型
}
}
throw new NoSuchFieldException("No such field: " + clazz.getName() + '.' + propertyName);
}
/**
* 暴力获取对象变量值,忽略private,protected修饰符的限制.
*
* @throws NoSuchFieldException 如果没有该Field时抛出.
*/
public static Object forceGetProperty(Object object, String propertyName) throws NoSuchFieldException {
Assert.notNull(object);
Assert.hasText(propertyName);
Field field = getDeclaredField(object, propertyName);
boolean accessible = field.isAccessible();
field.setAccessible(true);
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {
logger.info("error wont' happen");
}
field.setAccessible(accessible);
return result;
}
/**
* 暴力设置对象变量值,忽略private,protected修饰符的限制.
*
* @throws NoSuchFieldException 如果没有该Field时抛出.
*/
public static void forceSetProperty(Object object, String propertyName, Object newValue)
throws NoSuchFieldException {
Assert.notNull(object);
Assert.hasText(propertyName);
Field field = getDeclaredField(object, propertyName);
boolean accessible = field.isAccessible();
field.setAccessible(true);
try {
field.set(object, newValue);
} catch (IllegalAccessException e) {
logger.info("Error won't happen");
}
field.setAccessible(accessible);
}
/**
* 暴力调用对象函数,忽略private,protected修饰符的限制.
*
* @throws NoSuchMethodException 如果没有该Method时抛出.
*/
public static Object invokePrivateMethod(Object object, String methodName, Object... params)
throws NoSuchMethodException {
Assert.notNull(object);
Assert.hasText(methodName);
Class[] types = new Class[params.length];
for (int i = 0; i < params.length; i++) {
types[i] = params[i].getClass();
}
Class clazz = object.getClass();
Method method = null;
for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
method = superClass.getDeclaredMethod(methodName, types);
break;
} catch (NoSuchMethodException e) {
// 方法不在当前类定义,继续向上转型
}
}
if (method == null)
throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName);
boolean accessible = method.isAccessible();
method.setAccessible(true);
Object result = null;
try {
result = method.invoke(object, params);
} catch (Exception e) {
ReflectionUtils.handleReflectionException(e);
}
method.setAccessible(accessible);
return result;
}
/**
* 按Filed的类型取得Field列表.
*/
public static List<Field> getFieldsByType(Object object, Class type) {
List<Field> list = new ArrayList<Field>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getType().isAssignableFrom(type)) {
list.add(field);
}
}
return list;
}
/**
* 按FiledName获得Field的类型.
*/
public static Class getPropertyType(Class type, String name) throws NoSuchFieldException {
return getDeclaredField(type, name).getType();
}
/**
* 获得field的getter函数名称.
*/
public static String getGetterName(Class type, String fieldName) {
Assert.notNull(type, "Type required");
Assert.hasText(fieldName, "FieldName required");
if (type.getName().equals("boolean")) {
return "is" + StringUtils.capitalize(fieldName);
} else {
return "get" + StringUtils.capitalize(fieldName);
}
}
/**
* 获得field的getter函数,如果找不到该方法,返回null.
*/
public static Method getGetterMethod(Class type, String fieldName) {
try {
return type.getMethod(getGetterName(type, fieldName));
} catch (NoSuchMethodException e) {
logger.error(e.getMessage(), e);
}
return null;
}
// ------------------------------------------------------ Private Variables
/**
* Dummy collection from the Commons Collections API, to force a
* ClassNotFoundException if commons-collections.jar is not present in the
* runtime classpath, and this class is the first one referenced.
* Otherwise, the ClassNotFoundException thrown by ConvertUtils or
* PropertyUtils can get masked.
*/
private static FastHashMap dummy = new FastHashMap();
/**
* The debugging detail level for this component.
* @deprecated BeanUtils now uses commons-logging for all log messages.
* Use your favorite logging tool to configure logging for
* this class.
*/
private static int debug = 0;
/**
* @deprecated BeanUtils now uses commons-logging for all log messages.
* Use your favorite logging tool to configure logging for
* this class.
*/
public static int getDebug() {
return (debug);
}
/**
* @deprecated BeanUtils now uses commons-logging for all log messages.
* Use your favorite logging tool to configure logging for
* this class.
*/
public static void setDebug(int newDebug) {
debug = newDebug;
}
// --------------------------------------------------------- Class Methods
/**
* <p>Clone a bean based on the available property getters and setters,
* even if the bean class itself does not implement Cloneable.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#cloneBean
*/
public static Object cloneBean(Object bean)
throws IllegalAccessException, InstantiationException,
InvocationTargetException, NoSuchMethodException {
return BeanUtilsBean.getInstance().cloneBean(bean);
}
/**
* <p>Copy property values from the origin bean to the destination bean
* for all cases where the property names are the same.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#copyProperties
*/
public static void copyProperties(Object dest, Object orig)
throws IllegalAccessException, InvocationTargetException {
BeanUtilsBean.getInstance().copyProperties(dest, orig);
}
/**
* <p>Copy the specified property value to the specified destination bean,
* performing any type conversion that is required.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#copyProperty
*/
public static void copyProperty(Object bean, String name, Object value)
throws IllegalAccessException, InvocationTargetException {
BeanUtilsBean.getInstance().copyProperty(bean, name, value);
}
/**
* <p>Return the entire set of properties for which the specified bean
* provides a read method.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#describe
*/
public static Map describe(Object bean)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().describe(bean);
}
/**
* <p>Return the value of the specified array property of the specified
* bean, as a String array.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#getArrayProperty
*/
public static String[] getArrayProperty(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().getArrayProperty(bean, name);
}
/**
* <p>Return the value of the specified indexed property of the specified
* bean, as a String.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#getIndexedProperty(Object, String)
*/
public static String getIndexedProperty(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().getIndexedProperty(bean, name);
}
/**
* Return the value of the specified indexed property of the specified
* bean, as a String. The index is specified as a method parameter and
* must *not* be included in the property name expression
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#getIndexedProperty(Object, String, int)
*/
public static String getIndexedProperty(Object bean,
String name, int index)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().getIndexedProperty(bean, name, index);
}
/**
* </p>Return the value of the specified indexed property of the specified
* bean, as a String.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#getMappedProperty(Object, String)
*/
public static String getMappedProperty(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().getMappedProperty(bean, name);
}
/**
* </p>Return the value of the specified mapped property of the specified
* bean, as a String.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#getMappedProperty(Object, String, String)
*/
public static String getMappedProperty(Object bean,
String name, String key)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().getMappedProperty(bean, name, key);
}
/**
* <p>Return the value of the (possibly nested) property of the specified
* name, for the specified bean, as a String.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#getNestedProperty
*/
public static String getNestedProperty(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().getNestedProperty(bean, name);
}
/**
* <p>Return the value of the specified property of the specified bean,
* no matter which property reference format is used, as a String.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#getProperty
*/
public static String getProperty(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().getProperty(bean, name);
}
/**
* <p>Return the value of the specified simple property of the specified
* bean, converted to a String.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#getSimpleProperty
*/
public static String getSimpleProperty(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().getSimpleProperty(bean, name);
}
/**
* <p>Populate the JavaBeans properties of the specified bean, based on
* the specified name/value pairs.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#populate
*/
public static void populate(Object bean, Map properties)
throws IllegalAccessException, InvocationTargetException {
BeanUtilsBean.getInstance().populate(bean, properties);
}
/**
* <p>Set the specified property value, performing type conversions as
* required to conform to the type of the destination property.</p>
*
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @see BeanUtilsBean#setProperty
*/
public static void setProperty(Object bean, String name, Object value)
throws IllegalAccessException, InvocationTargetException {
BeanUtilsBean.getInstance().setProperty(bean, name, value);
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
//List<Field> list=BeanUtils.
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -