您的位置:首页 > 移动开发 > Objective-C

Object对象如何类获取对应类的属性值

2016-12-19 11:02 495 查看

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里的属性值):




注:

在运行的过程中有遇到有遇到一个问题,

报错:

can not access a member of class com.hc.apps.depositManage.entity.Deposit with modifiers “private”

解决方法:

加上 f.setAccessible(true);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java