黑马程序员技术交流社区
标题:
用反射获取类属性的值
[打印本页]
作者:
傲凡玉蝶
时间:
2015-5-23 22:34
标题:
用反射获取类属性的值
import java.lang.reflect.Field;
public class Reflect {
/*
* 一次性获取类属性的值
*/
public static void main(String[] args) throws Exception {
RefPoint rpt = new RefPoint(3, 5, "abc");
Field[] f = rpt.getClass().getDeclaredFields();
for (int i=0;i<f.length; i++)
{
f[i].setAccessible(true);
System.out.println(f[i].get(rpt));
}
}
}
class RefPoint{
private int x;
public int y;
private String z;
public RefPoint(int x, int y, String z) {
super();
this.x = x;
this.y = y;
this.z = z;
}
}
输出结果:
3
5
abc
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2