在处理数据导入时,常常需要将Map对象转换为JavaBean,以便于处理和存储数据。具体来说,已知Map的key代表JavaBean的字段名,value代表对应的值,但并不了解JavaBean的内部字段排列。因此,需要编写一个工具方法来完成这个任务。首先,来看一下如何将JavaBean对象转化为Map:SuppressWarnings({ "rawtypes", "...
java bean怎么转化为map 不用第三方
在处理数据导入时,常常需要将Map对象转换为JavaBean,以便于处理和存储数据。具体来说,已知Map的key代表JavaBean的字段名,value代表对应的值,但并不了解JavaBean的内部字段排列。因此,需要编写一个工具方法来完成这个任务。
首先,来看一下如何将JavaBean对象转化为Map:
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map convertBean(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Class type = bean.getClass();
Map returnMap = new HashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i< propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName, result);
} else {
returnMap.put(propertyName, "");
}
}
}
return returnMap;
}
接着,我们来看看如何将Map对象转换为JavaBean:
@SuppressWarnings("rawtypes")
public static Object convertMap(Class type, Map map) throws IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException {
BeanInfo beanInfo = Introspector.getBeanInfo(type);
// 获取类属性
Object obj = 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;
descriptor.getWriteMethod().invoke(obj, args);
}
}
return obj;
}
以上两个方法分别完成了JavaBean对象与Map之间的相互转换,适用于处理数据导入时的数据转换需求。2024-12-05