下面这个程序是把ReflectPoint对象里的String类型的变量的值中的a替换成b,为什什么只有public的能改
private 或 没有修饰的怎么改?
public class ReflectTest {
public static void main(String[] args) throws Exception {
ReflectPoint rfp=new ReflectPoint(5,8);
replace(rfp);
Field rfpA=rfp.getClass().getDeclaredField("a");
rfpA.setAccessible(true);
System.out.println(rfpA.get(rfp));
//System.out.println(rfp.a);
System.out.println(rfp.b);
System.out.println(rfp.c);
}
private static void replace(Object rfp) throws Exception {
Field[] fields=rfp.getClass().getFields();
for(Field field: fields){
if(field.getType()==String.class){
String strValue=(String)(field.get(rfp));
String newStr=strValue.replace('b', 'a');
field.set(rfp, newStr);
}
}
}
}
public class ReflectPoint {
private int x;
public int y;
private String a="ball"; //改变后要成:"aall"
public String b="basketball"; //改变后:"aasketaall"
String c="I like sb";
public ReflectPoint(int x,int y){
this.x=x;
this.y=y;
}
} |