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));
}
}