MongoDBUtils { public static <T> T documentToBean(Document document, 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 = document.get(varName); if (object != null) { setProperty(bean, varName, object); } } return bean; }  static Document beanToDocument(T bean); static T documentToBean(Document document, T bean); static void setProperty(T bean, String varName, T object);  }
@Test public void testDocumentToBean() { String data = "测试数据"; String msg = "成功了"; Integer code = Integer.valueOf(10); ResultBean<String> resultBean = new ResultBean(data); resultBean.setMsg(msg); try { Document doc = MongoDBUtils.beanToDocument(resultBean); assertEquals(doc.get("data", String.class), resultBean.getData()); assertEquals(doc.get("msg", String.class), resultBean.getMsg()); assertEquals(doc.get("rtnCode", Integer.class), Integer.valueOf(resultBean.getRtnCode())); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } }