| 
 
| 本帖最后由 李培根 于 2013-1-2 18:42 编辑 
 将任意一个对象中的所有String类型的成员变量所对应的字符串内容中的"b"改成"a"。
 
 public class Reflect1 {
 public static void main(String[] args) throws Exception {
 ReflectPoint pt1 = new ReflectPoint();
 
 changeStringValue(pt1);
 System.out.println(pt1);//打印结果还是abc:ball:def,没有改变仔细看了也没查出错误,求指教
 }
 
 
 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 {
 
 String str1 = "abc";
 String str2 = "ball";
 String str3 = "def";
 @Override
 public String toString() {
 return str1 + ":" + str2 + ":" + str3;
 }
 
 }
 | 
 |