class.getDeclaredFields()與class.getFields()


* getFields()與getDeclaredFields()區別:getFields()只能訪問類中聲明為公有的字段,私有的字段它無法訪問.getDeclaredFields()能訪問類中所有的字段,與public,private,protect無關  

* getMethods()與getDeclaredMethods()區別:getMethods()只能訪問類中聲明為公有的方法,私有的方法它無法訪問,能訪問從其它類繼承來的公有方法.getDeclaredFields()能訪問類中所有的字段,與public,private,protect無關,不能訪問從其它類繼承來的方法  

* getConstructors()與getDeclaredConstructors()區別:getConstructors()只能訪問類中聲明為public的構造函數.getDeclaredConstructors()能訪問類中所有的構造函數,與public,private,protect無關 

package test;

public class Point1 {
    private int x;
    public int y;
    public String a="asdasd";
    public Point1() {}
    public Point1(int i, int j) {
        super();
        this.x=i;
        this.y=j;
    }
}
public class fieldTest {
    public static void main(String[] args) throws  Exception {
        Point1 point=new Point1(5, 10);
        Field fieldY=point.getClass().getField("y");      //  y字段公有
        System.out.println(fieldY);
        System.out.println(fieldY.get(point));
        
        Field fieldX=point.getClass().getDeclaredField("x");   //x字段私有
        fieldX.setAccessible(true);                            //AccessibleTest類中的成員變量為private,故必須進行此操作  
        System.out.println(fieldX.get(point));                 //如果沒有在獲取Field之前調用setAccessible(true)方法,異常
        
        Point1 point2=new Point1();
        
        Field[] fields=point.getClass().getFields();          //把Point1函數中的String字段做改動
        for(Field field:fields) {                           
            if (field.getType()==String.class) {              
                String oldValue =(String) field.get(point2);          
                String newVaule =oldValue.replace('a', 'b');
                field.set(point2, newVaule);
                System.out.println(field.get(point2));
            }
        }
        
    }
}
輸出結果
public int test.Point1.y
10
5
bsdbsd

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。