反射(3)クラスの属性の反射を理解し,次の属性があればReflectPointのstr内のa->z
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 "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="
+ str3 + ", x=" + x + ", y=" + y + "]";
}
}
-------------------------------------------------
public static void changStringValue(Object object) throws IllegalArgumentException, IllegalAccessException{
Field[] fields=object.getClass().getDeclaredFields();
for(Field field:fields){
if(field.getType()==String.class){
String oldStr=(String)field.get(object);
String newValue=oldStr.replace('b', 'm');
field.set(object,newValue);// set , ,
}
}
}
main関数の内容は次のとおりです.
ReflectPoint reflectPoint=new ReflectPoint(3,5);
changStringValue(reflectPoint);
System.out.println(reflectPoint);