import java.lang.reflect.Field;
/**
* @author dell
*
*/
public class FieldTest {
class point{
private int xx;
public int yy;
public point(int x,int y){
this.xx=x;
this.yy=y;
}
}
public static void main(String[] args) throws Exception {
FieldTest f=new FieldTest();
FieldTest.point p=f.new point(3,5);
//获取对象p的yy属性值
Field field= p.getClass().getField("yy");
//field :p.getClass() 是类 ,所以field是类上的属性,不是对象p的属性,打印出来的
//不是5 而是 public int com.hlmedicals.app.test.api.ssz.FieldTest$point.yy
System.out.println(field);
//要想获取对象的属性 我们先要获取类上的属性,在通过这个类上的属性.get(对象名称) 获取对象的属性值
System.out.println(field.get(p));
//获取对象p的xx属性值 注意xx是私有的
//下面 会报Exception in thread "main" java.lang.NoSuchFieldException: xx
//原因是xx是私有的 ,获取类的属性时候 不能用 getfeild 得用getDeclaredField
// Field fieldxx=p.getClass().getField("xx");
// System.out.println(fieldxx.get(p));
Field fieldxx=p.getClass().getDeclaredField("xx");
//我们这样还是不能把私有的属性值拿出来 回报java.lang.IllegalAccessException:
//Class com.hlmedicals.app.test.api.ssz.FieldTest can not access a member of class com.hlmedicals.app.test.api.ssz.FieldTest$point with modifiers "private
//System.out.println(fieldxx.get(p));
//我们要在获取私有属性前 ,设置setAccessible(true) 这样我们能取到3
fieldxx.setAccessible(true);
System.out.println(fieldxx.get(p));
}
}
/**
* @author dell
*
*/
public class FieldTest {
class point{
private int xx;
public int yy;
public point(int x,int y){
this.xx=x;
this.yy=y;
}
}
public static void main(String[] args) throws Exception {
FieldTest f=new FieldTest();
FieldTest.point p=f.new point(3,5);
//获取对象p的yy属性值
Field field= p.getClass().getField("yy");
//field :p.getClass() 是类 ,所以field是类上的属性,不是对象p的属性,打印出来的
//不是5 而是 public int com.hlmedicals.app.test.api.ssz.FieldTest$point.yy
System.out.println(field);
//要想获取对象的属性 我们先要获取类上的属性,在通过这个类上的属性.get(对象名称) 获取对象的属性值
System.out.println(field.get(p));
//获取对象p的xx属性值 注意xx是私有的
//下面 会报Exception in thread "main" java.lang.NoSuchFieldException: xx
//原因是xx是私有的 ,获取类的属性时候 不能用 getfeild 得用getDeclaredField
// Field fieldxx=p.getClass().getField("xx");
// System.out.println(fieldxx.get(p));
Field fieldxx=p.getClass().getDeclaredField("xx");
//我们这样还是不能把私有的属性值拿出来 回报java.lang.IllegalAccessException:
//Class com.hlmedicals.app.test.api.ssz.FieldTest can not access a member of class com.hlmedicals.app.test.api.ssz.FieldTest$point with modifiers "private
//System.out.println(fieldxx.get(p));
//我们要在获取私有属性前 ,设置setAccessible(true) 这样我们能取到3
fieldxx.setAccessible(true);
System.out.println(fieldxx.get(p));
}
}