MongoDBUtils { public static <T> Document beanToDocument(T bean) throws IllegalArgumentException, IllegalAccessException { if (bean == null) { return null; } Document document = new Document(); Field[] fields = bean.getClass().getDeclaredFields(); for (Field field : fields) { String varName = field.getName(); boolean accessFlag = field.isAccessible(); if (!accessFlag) { field.setAccessible(true); } Object param = field.get(bean); if (param == null || "serialVersionUID".equals(field.getName()) || field.getName().contains("bitField")) { continue; } else if (param instanceof Integer) { int value = ((Integer) param).intValue(); document.put(varName, value); } else if (param.getClass() == int.class) { int value = (int) param; document.put(varName, value); } else if (param instanceof String) { String value = (String) param; document.put(varName, value); } else if (param instanceof Double) { double value = ((Double) param).doubleValue(); document.put(varName, value); } else if (param.getClass() == double.class) { double value = (double) param; document.put(varName, value); } else if (param instanceof Float) { float value = ((Float) param).floatValue(); document.put(varName, value); } else if (param.getClass() == float.class) { float value = (float) param; document.put(varName, value); } else if (param instanceof Long) { long value = ((Long) param).longValue(); document.put(varName, value); } else if (param.getClass() == long.class) { long value = (long) param; document.put(varName, value); } else if (param instanceof Boolean) { boolean value = ((Boolean) param).booleanValue(); document.put(varName, value); } else if (param.getClass() == boolean.class) { boolean value = (boolean) param; document.put(varName, value); } else if (param instanceof Date) { Date value = (Date) param; document.put(varName, value.getTime()); } else if (param instanceof LocalDateTime) { LocalDateTime dataTimeValue = (LocalDateTime) param; document.put(varName, CommonUtils.localDateTimeToMills(dataTimeValue)); } field.setAccessible(accessFlag); } return document; }  static Document beanToDocument(T bean); static T documentToBean(Document document, T bean); static void setProperty(T bean, String varName, T object);  }
@Test public void testBeanToDocument() { String data = "测试数据"; String msg = "成功了"; Integer code = Integer.valueOf(10); Document doc = new Document(); doc.put("data", data); doc.put("msg", msg); doc.put("rtnCode", code); ResultBean<String> resultBean = new ResultBean(1, ""); try { resultBean = MongoDBUtils.documentToBean(doc, resultBean); assertEquals(resultBean.getData(), data); assertEquals(resultBean.getMsg(), msg); assertEquals(Integer.valueOf(resultBean.getRtnCode()), code); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } }