天天看點

java bean的反射類_java基于反射的Map轉Bean的工具類

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;

public class Transformation {

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

}

}

@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;

}

}