java实现bean实体与map集合相互转换
方法一
//bean裝換成map
public static Map<?, ?> objectToMap2(Object obj) { ?
??????? if(obj == null) ?
??????????? return null;? ?
??????? return new org.apache.commons.beanutils.BeanMap(obj); ?
??? } ?
?? 方法二
//bean裝換成map
??? public static Map<String, Object> objectToMap(Object obj)? {
?? ??? ?Map<String, Object> map = new HashMap<String, Object>();
?? ??? ?try{
?? ??? ??? ?if (obj == null)
?? ???????????? return map;
?? ???????? BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
?? ???????? PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
?? ???????? for (PropertyDescriptor property : propertyDescriptors) {
?? ???????????? String key = property.getName();
?? ???????????? if (key.compareToIgnoreCase("class") == 0) {
?? ???????????????? continue;
?? ???????????? }
?? ???????????? Method getter = property.getReadMethod();
?? ??????????? // System.out.println("key:" + key + ",getter:" + getter);
?? ???????????? Object value = getter != null ? getter.invoke(obj) : null;
?? ???????????? map.put(key, value);
?? ???????? }
?? ??? ?}catch(Exception e){
?? ??? ??? ?e.printStackTrace();
?? ??? ?}
?? ??? ?return map;
??? }
//map裝換成bean
public static Object mapToObject(Map<String, Object> map, Object bean) throws Exception {?? ?
??????? if (map == null) ?
??????????? return null; ?
??????? Object obj = bean.getClass().newInstance(); ?
??????? org.apache.commons.beanutils.BeanUtils.populate(obj, map);
? ?
??????? return obj; ?
??? }
總結
以上是生活随笔為你收集整理的java实现bean实体与map集合相互转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 获取oracle mysql
- 下一篇: java实现base64加密解密