在做导入的时候,遇到了需要将map对象转化 成javabean的问题,也就是说,不清楚javabean的内部字段排列,只知道map的 key代表javabean的字段名,value代表值。
那现在就需要用转化工具了。是通用的哦!
首先来看 JavaBean 转化成Map的方法:
[java] view plaincopy
[java]
/**
* 将一个 JavaBean 对象转化为一个 Map
* @param bean 要转化的JavaBean 对象
* @return 转化出来的 Map 对象
* @throws IntrospectionException 如果分析类属性失败
* @throws IllegalAccessException 如果实例化 JavaBean 失败
* @throws InvocationTargetException 如果调用属性的 setter 方法失败
*/
@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对象的方法:="" [java]="" view="" plaincopy="" [java]="" *="" *="" 将一个="" map="" 对象转化为一个="" javabean="" *="" @param="" type="" 要转化的类型="" *="" @param="" map="" 包含属性值的="" map="" *="" @return="" 转化出来的="" javabean="" 对象="" *="" @throws="" introspectionexception="" 如果分析类属性失败="" *="" @throws="" illegalaccessexception="" 如果实例化="" javabean="" 失败="" *="" @throws="" instantiationexception="" 如果实例化="" javabean="" 失败="" *="" @throws="" invocationtargetexception="" 如果调用属性的="" setter="" 方法失败="" */="" @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;">< 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="">
这应该不是java的annotation.应该是hibernate或者是spring的,spring的可能性更大一些.但是我翻遍源码也没有找到,可能是自己定义的.
用户登录
还没有账号?立即注册
用户注册
投稿取消
文章分类: |
|
还能输入300字
上传中....