引用的包为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);
}
本文介绍如何使用Java反射API遍历对象属性并利用Jackson库将对象转换为Map。通过示例代码展示了如何获取对象的所有属性名称及类型,并跳过特定属性。
1223

被折叠的 条评论
为什么被折叠?



