遍歷物件中的所有屬性,型別並顯示值
阿新 • • 發佈:2019-01-08
引用的包為java.beans.Introspector
遍歷物件屬性,並獲取其中的值Utils.covertValue(test, Map.class);為公共類
//propertyDesc[i].getName()名字, propertyDesc[i].getPropertyType()型別
public void getTest(){
//例項化一個類(其中有個class屬性)
People people= new People();
people.setId("123");
people.setAppId("123");
try {
People test = mongoFileManager.getTest("7897897891");
Map covertValue = Utils.covertValue(test, Map.class);
//開始迭代屬性
BeanInfo beanInfo = Introspector.getBeanInfo(People.class);
PropertyDescriptor[] propertyDesc = beanInfo.getPropertyDescriptors();
//迴圈展示(超類中有個class屬性要略過)
for (PropertyDescriptor propertyDescriptor : propertyDesc) {
if (propertyDesc[i].getName().
compareToIgnoreCase("class") == 0)
continue;
System.out.println(propertyDescriptor.getName()+"----"
+covertValue.get (propertyDescriptor.getName()));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
轉化類引入包
com.fasterxml.jackson.databind.ObjectMapper
private static ObjectMapper mapper = new ObjectMapper();
public static <T> T covertValue(Object value, Class<T> toType) {
return mapper.convertValue(value, toType);
}