遍歷對象中的所有屬性,類型並顯示值

引用的包爲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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章