时间:2021-07-01 10:21:17 帮助过:19人阅读
/** * 将DBObject转换成Bean对象 * */ public static <T> T dbObjectToBean(DBObject dbObject, T bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { return null; } Field[] fields = bean.getClass().getDeclaredFields(); for (Field field : fields) { String varName = field.getName(); Object object = dbObject.get(varName); if (object != null) { BeanUtils.setProperty(bean, varName, object); } } return bean; } // 取出Mongo中的属性值,为bean赋值 public static <T> void setProperty(T bean, String varName, T object) { varName = varName.substring(0, 1).toUpperCase() + varName.substring(1); try { String type = object.getClass().getName(); // 类型为String if (type.equals("java.lang.String")) { Method m = bean.getClass().getMethod("get" + varName); String value = (String) m.invoke(bean); if (value == null) { m = bean.getClass() .getMethod("set" + varName, String.class); m.invoke(bean, object); } } // 类型为Integer if (type.equals("java.lang.Integer")) { Method m = bean.getClass().getMethod("get" + varName); String value = (String) m.invoke(bean); if (value == null) { m = bean.getClass().getMethod("set" + varName, Integer.class); m.invoke(bean, object); } } // 类型为Boolean if (type.equals("java.lang.Boolean")) { Method m = bean.getClass().getMethod("get" + varName); String value = (String) m.invoke(bean); if (value == null) { m = bean.getClass().getMethod("set" + varName, Boolean.class); m.invoke(bean, object); } } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
MONGODB(四)——DBObject与JavaBean转换
标签: