代码:
//遍历类中所有字段信息 https://blog.csdn.net/weixin_34346099/article/details/94036015
public static void reflect(Object o){
//获取参数类
Class cls = o.getClass();
//将参数类转换为对应属性数量的Field类型数组(即该类有多少个属性字段 N 转换后的数组长度即为 N)
Field[] fields = cls.getDeclaredFields();
for(int i = 0;i < fields.length; i ++){
Field f = fields[i];
f.setAccessible(true);
try {
//f.getName()得到对应字段的属性名,f.get(o)得到对应字段属性值,f.getGenericType()得到对应字段的类型
// System.out.println("属性名:"+f.getName()+";属性值:"+f.get(o)+";字段类型:" + f.getGenericType());
Log.i("xwg","属性名:"+f.getName()+";属性值:"+f.get(o)+";字段类型:" + f.getGenericType());
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("xwg","ReflectUtil error:"+e.toString());
}
}
}
调用:
DeviceBean device=new DeviceBean();
device.setName("aa");
device.setAge(44);
ReflectUtil.reflect(devie);