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