setAccessible(true)安全檢查不通過 Bean轉Map
阿新 • • 發佈:2018-11-30
setAccessible(true)安全檢查不通過 Bean轉Map
public static Map<String, Object> beanToMap(Object object) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); Class cls = object.getClass(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); map.put(field.getName(), field.get(object)); } return map; }
上面的程式碼使用了setAccessible(true)公司安全檢查不通過
public static Map<String, Object> beanToMap(Object obj) { if (obj == null) { return null; } Map<String, Object> map = new HashMap<String, Object>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); // 過濾class屬性 if (!key.equals("class")) { // 得到property對應的getter方法 Method getter = property.getReadMethod(); Object value = getter.invoke(obj); map.put(key, value); } } } catch (Exception e) { logger.error("transBean2Map Error ", e); } return map; }
使用這種方式,安全可靠