本帖最后由 sunhaodi 于 2012-6-23 22:38 编辑
import java.lang.reflect.Field;
public class ReflectDemo {
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Person p = new Person(3,4);
Field filedx = p.getClass().getField("x");
System.out.println(filedx.get(p)); //这个代码我和张孝祥老师写的一样, 为什么运行不出来会报错啊
// Field filedy= p.getClass().getDeclaredField("y");
// filedy.setAccessible(true);
// System.out.println(filedy.get(p));
}
}
class Person{
private int x;
private int y;
private String str1 = "aaaaaaa";
private String str2 ="ddddddd";
public Person(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return str1+".............."+str2;
}
}
看注释, 不明白什么情况,检查半天,一模一样啊 |
|