public class ReflectTest { public static void main(String[] args) throws Exception { //成员变量的反射 ReflectPoint pt1 = new ReflectPoint(3, 5); Field fieldY = pt1.getClass().getField("y"); System.out.println(fieldY.get(pt1));//5 因为y是公有属性,可以直接得到 Field fieldX = pt1.getClass().getDeclaredField("x"); fieldX.setAccessible(true); System.out.println(fieldX.get(pt1));//3 x是私有属性,使用getDeclaredField,然后setAcces sible(true) changeStringValue(pt1); System.out.println(pt1);//aall:aasketaall:itcast } private static void changeStringValue(Object obj) throws Exception { Field[] fields = obj.getClass().getFields(); for(Field field :fields){ if(field.getType()==String.class){ String oldValue = (String) field.get(obj); String newValue = oldValue.replace('b', 'a'); field.set(obj, newValue); } } }}public class ReflectPoint { private int x; public int y; public String str1 = "ball"; public String str2 = "basketball"; public String str3 = "itcast"; public ReflectPoint(int x, int y) { super(); this.x = x; this.y = y; } @Override public String toString(){ return str1+":"+str2+":"+str3; } }