Object对象如何类获取对应类的属性值
public void test() throws NoSuchFieldException, IllegalAccessException {
Deposit deposit=new Deposit();
deposit.setBusinessType("业务类型");
deposit.setDescription("业务描述");
Object object=deposit;
Class<?> s=object.getClass();
System.out.println("类名"+s);
for (Field f:object.getClass().getDeclaredFields()){ //遍历通过反射获取object的类中的属性名
f.setAccessible(true); //设置改变属性为可访问
if(f.getName().equals("businessType")){
System.out.println("属性值"+f.get(object));
}
}
运行结果(成功获取object里的属性值):
![这里写图片描述](https://img-blog.csdn.net/20161219105954771?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvRFVEVWZpbmU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
注:
在运行的过程中有遇到有遇到一个问题,
报错:
can not access a member of class com.hc.apps.depositManage.entity.Deposit with modifiers “private”
解决方法:
加上 f.setAccessible(true);