package com.kmall.common.utils;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
/**
* bean 对象工具类
* 描述:
*
* @author Scott
* @version 1.0
* @since 1.0.0
*/
public class MyBeanUtils extends PropertyUtilsBean {
/**
* 主要功能:转换
* 注意事项:无
*
* @param dest 结果对象
* @param orig 来源对象
* @throws IllegalAccessException 异常
* @throws InvocationTargetException 异常
*/
@SuppressWarnings("all")
private static void convert(Object dest, Object orig)
throws IllegalAccessException,
InvocationTargetException {
// Validate existence of the specified beans
if (dest == null) {
throw new IllegalArgumentException("No destination bean specified");
}
if (orig == null) {
throw new IllegalArgumentException("No origin bean specified");
}
// Copy the properties, converting as necessary
if (orig instanceof DynaBean) {
DynaProperty[] origDescriptors = ((DynaBean) orig).getDynaClass().getDynaProperties();
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
if (PropertyUtils.isWriteable(dest, name)) {
Object value = ((DynaBean) orig).get(name);
try {
getInstance().setSimpleProperty(dest, name, value);
} catch (Exception e) {
; // Should not happen
}
}
}
} else if (orig instanceof Map) {
Iterator names = ((Map) orig).keySet().iterator();
while (names.hasNext()) {
String name = (String) names.next();
if (PropertyUtils.isWriteable(dest, name)) {
Object value = ((Map) orig).get(name);
try {
getInstance().setSimpleProperty(dest, name, value);
} catch (Exception e) {
; // Should not happen
}
}
}
} else { /* if (orig is a standard JavaBean) */
PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(
orig);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
// String type = origDescriptors[i].getPropertyType().toString();
if ("class".equals(name)) {
continue; // No point in trying to set an object's class
}
if (PropertyUtils.isReadable(orig, name)
&& PropertyUtils.isWriteable(dest, name)) {
try {
Object value = PropertyUtils.getSimpleProperty(orig,
name);
getInstance().setSimpleProperty(dest, name, value);
} catch (IllegalArgumentException ie) {
; // Should not happen
} catch (Exception e) {
; // Should not happen
}
}
}
}
}
/**
* 对象拷贝
* 数据对象空值不拷贝到目标对象
*
* @param databean 数据对象
* @param tobean 返回对象
* @throws Exception 异常
*/
public static void copyBeanNotNull2Bean(Object databean, Object tobean)
throws Exception {
PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(
databean);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
// String type = origDescriptors[i].getPropertyType().toString();
if ("class".equals(name)) {
continue; // No point in trying to set an object's class
}
if (PropertyUtils.isReadable(databean, name)
&& PropertyUtils.isWriteable(tobean, name)) {
try {
Object value = PropertyUtils.getSimpleProperty(databean,
name);
if (value != null) {
getInstance().setSimpleProperty(tobean, name, value);
}
} catch (IllegalArgumentException ie) {
; // Should not happen
} catch (Exception e) {
; // Should not happen
}
}
}
}
/**
* 把orig和dest相同属性的value复制到dest中
*
* @param dest 结果
* @param orig 来源
* @throws Exception 异常
*/
public static void copyBean2Bean(Object dest, Object orig)
throws Exception {
convert(dest, orig);
}
/**
* 主要功能:bean 转换成 map
* 注意事项:无
*
* @param map map对象
* @param bean bean对象
*/
@SuppressWarnings("all")
public static void copyBean2Map(Map map, Object bean) {
PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
for (int i = 0; i < pds.length; i++) {
PropertyDescriptor pd = pds[i];
String propname = pd.getName();
try {
Object propvalue = PropertyUtils.getSimpleProperty(bean,
propname);
map.put(propname, propvalue);
} catch (IllegalAccessException e) {
// e.printStackTrace();
} catch (InvocationTargetException e) {
// e.printStackTrace();
} catch (NoSuchMethodException e) {
// e.printStackTrace();
}
}
}
/**
* 主要功能:bean 转换成 map
* 注意事项:无
*
* @param map map对象
* @param bean bean对象
*/
@SuppressWarnings("all")
public static void copyBean2Map(Map map, Object bean,
List fieldNameList) {
for (int i = 0; i < fieldNameList.size(); i++) {
String oldPropname = fieldNameList.get(i);
String propname = StringUtils.lineToHump(oldPropname);
try {
Object propvalue = getProp(bean, propname);
map.put(oldPropname, propvalue);
} catch (Exception e) {
}
}
}
/**
* 将Map内的key与Bean中属性相同的内容复制到BEAN中
*
* @param bean Object
* @param properties Map
*/
@SuppressWarnings("all")
public static void copyMap2Bean(Object bean, Map properties) {
if ((bean == null) || (properties == null)) {
return;
}
// map key 集合
Iterator names = properties.keySet().iterator();
// 逐个处理key转换
while (names.hasNext()) {
String name = (String) names.next();
if (name == null) {
continue;
}
Object value = properties.get(name);
try {
// name转换成驼峰
name = StringUtils.lineToHump(name);
// 获取属性类型
Class clazz = PropertyUtils.getPropertyType(bean, name);
if (null == clazz) {
continue;
}
String className = clazz.getName();
// 时间戳
if (className.equalsIgnoreCase("java.sql.Timestamp")) {
if (value == null || value.equals("")) {
continue;
}
}
// 整型INT
if (className.equalsIgnoreCase("int")) {
if (value == null || value.equals("")) {
continue;
} else {
value = ((BigDecimal) value).intValue();
}
}
// long型
if (className.equalsIgnoreCase("long")) {
if (value == null || value.equals("")) {
continue;
} else {
value = ((BigDecimal) value).longValue();
}
}
// long型
if (className.equalsIgnoreCase("java.lang.Long")) {
if (value == null || value.equals("")) {
continue;
} else {
value = ((BigDecimal) value).longValue();
}
}
// long型
if (className.equalsIgnoreCase("java.lang.Integer")) {
if (value == null || value.equals("")) {
continue;
} else {
value = Integer.parseInt(value + "");
}
}
// 属性赋值
getInstance().setSimpleProperty(bean, name, value);
} catch (Exception e) {
continue;
}
}
}
/**
* 自动转Map key值大写
* 将Map内的key与Bean中属性相同的内容复制到BEAN中
*
* @param bean Object
* @param properties Map
* @throws IllegalAccessException 异常
* @throws InvocationTargetException 异常
*/
@SuppressWarnings("all")
public static void copyMap2BeanNobig(Object bean, Map properties)
throws IllegalAccessException,
InvocationTargetException {
// Do nothing unless both arguments have been specified
if ((bean == null) || (properties == null)) {
return;
}
// Loop through the property name/value pairs to be set
Iterator names = properties.keySet().iterator();
while (names.hasNext()) {
String name = (String) names.next();
// Identify the property name and value(s) to be assigned
if (name == null) {
continue;
}
Object value = properties.get(name);
// 命名应该大小写应该敏感(否则取不到对象的属性)
// name = name.toLowerCase();
try {
if (value == null) { // 不光Date类型,好多类型在null时会出错
continue; // 如果为null不用设 (对象如果有特殊初始值也可以保留?)
}
Class clazz = PropertyUtils.getPropertyType(bean, name);
if (null == clazz) { // 在bean中这个属性不存在
continue;
}
String className = clazz.getName();
// 临时对策(如果不处理默认的类型转换时会出错)
if (className.equalsIgnoreCase("java.util.Date")) {
value = new Date(
((java.sql.Timestamp) value).getTime());// wait to do:貌似有时区问题, 待进一步确认
}
// if (className.equalsIgnoreCase("java.sql.Timestamp")) {
// if (value == null || value.equals("")) {
// continue;
// }
// }
getInstance().setSimpleProperty(bean, name, value);
} catch (NoSuchMethodException e) {
continue;
}
}
}
/**
* Map内的key与Bean中属性相同的内容复制到BEAN中
* 对于存在空值的取默认值
*
* @param bean Object
* @param properties Map
* @param defaultValue String
* @throws IllegalAccessException 异常
* @throws InvocationTargetException 异常
*/
@SuppressWarnings("all")
public static void copyMap2Bean(Object bean, Map properties,
String defaultValue)
throws IllegalAccessException,
InvocationTargetException {
// Do nothing unless both arguments have been specified
if ((bean == null) || (properties == null)) {
return;
}
// Loop through the property name/value pairs to be set
Iterator names = properties.keySet().iterator();
while (names.hasNext()) {
String name = (String) names.next();
// Identify the property name and value(s) to be assigned
if (name == null) {
continue;
}
Object value = properties.get(name);
try {
Class clazz = PropertyUtils.getPropertyType(bean, name);
if (null == clazz) {
continue;
}
String className = clazz.getName();
if (className.equalsIgnoreCase("java.sql.Timestamp")) {
if (value == null || value.equals("")) {
continue;
}
}
if (className.equalsIgnoreCase("java.lang.String")) {
if (value == null) {
value = defaultValue;
}
}
getInstance().setSimpleProperty(bean, name, value);
} catch (NoSuchMethodException e) {
continue;
}
}
}
/**
* 获取一个类和其父类的所有属性
*
* @param clazz 要查找的类
* @return 属性列表
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static List findAllFieldsOfSelfAndSuperClass(Class clazz) {
Field[] fields = null;
List fieldList = new ArrayList();
while (true) {
if (clazz == null) {
break;
} else {
fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fieldList.add(fields[i]);
}
clazz = clazz.getSuperclass();
}
}
return fieldList;
}
/**
* 主要功能:把一个Bean对象转换成Map对象
* 注意事项:无
*
* @param obj 要转换的对象
* @param ignores 要忽略的属性值
* @return Map
*/
public static Map convertBean2Map(Object obj,
String[] ignores) {
Map map = new HashMap();
// Class clazz = obj.getClass();
List fieldList = findAllFieldsOfSelfAndSuperClass(
obj.getClass());
Field field = null;
try {
for (int i = 0; i < fieldList.size(); i++) {
field = fieldList.get(i);
// 定义fieldName是否在拷贝忽略的范畴内
boolean flag = false;
if (ignores != null && ignores.length != 0) {
flag = isExistOfIgnores(field.getName(), ignores);
}
if (!flag) {
Object value = getProp(obj, field.getName());
if (null != value
&& !StringUtils.EMPTY.equals(value.toString())) {
map.put(field.getName(), getProp(obj, field.getName()));
}
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return map;
}
/**
* 把一个Bean对象转换成Map对象
*
* @param obj 要转换的对象
* @return Map
*/
public static Map convertBean2Map(Object obj) {
return convertBean2Map(obj, null);
}
/**
* 主要功能: 把一个Bean对象转换成Map对象,忽略UID
* 注意事项:无
*
* @param obj 要转换的对象
* @return Map
*/
public static Map convertBean2MapForIngoreserialVersionUID(Object obj) {
return convertBean2Map(obj, new String[]{"serialVersionUID"});
}
/**
* 判断fieldName是否是ignores中排除的
*
* @param fieldName 要判断的属性值
* @param ignores 要忽略的列表
* @return 匹配为true
*/
private static boolean isExistOfIgnores(String fieldName,
String[] ignores) {
boolean flag = false;
for (String str : ignores) {
if (str.equals(fieldName)) {
flag = true;
break;
}
}
return flag;
}
/**
* 主要功能: 取得属性信息
* 注意事项:无
*
* @param clazz 要取得的类
* @param propertyName 要取得的属性
* @return 属性信息
*/
public static PropertyDescriptor getPropertyDescriptor(Class