import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
/**
*
* @ClassName: Transformation
* @Description: 数据类型转换
*
* @author yangtao
* @since 2016年10月19日 上午11:36:33
*
*/
public class Transformation {
/**
*
* @Title: setMethodValue
* @Description: 调用object的set方法,对obj的属性赋值
*
* @author yangtao
* @since 2016年10月19日 上午11:37:35
*
* @param obj
* @param method
* @param objects
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException void
*/
private static void setMethodValue(Object obj, Method method, Object objects) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (Timestamp.class.getName().equals(method.getParameterTypes()[0].getName())) {
if (null != objects && !"null".equals(objects)) {
method.invoke(obj, new Timestamp((long) objects));
}
} else if (Date.class.getName().equals(method.getParameterTypes()[0].getName())) {
if (null != objects && !"null".equals(objects)) {
method.invoke(obj, new Timestamp((long) objects));
}
} else if (java.sql.Date.class.getName().equals(method.getParameterTypes()[0].getName())) {
if (null != objects && !"null".equals(objects)) {
method.invoke(obj, new Timestamp((long) objects));
}
} else {
method.invoke(obj, objects);
}
}
/**
*
* @Title: convertMap
* @Description: 将一个 Map 对象转化为一个 JavaBean
*
* @author yangtao
* @since 2016年10月19日 上午11:37:24
*
* @param type
* @param map
* @return
* @throws IntrospectionException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws InvocationTargetException T
*/
@SuppressWarnings("rawtypes")
public static T convertMap(Class type, Map map) throws IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException {
BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
T instance = type.newInstance(); // 创建 JavaBean 对象
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
// 下面的 try起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
setMethodValue(instance, descriptor.getWriteMethod(), value);
}
}
return instance;
}
}