本帖最后由 郑传庆 于 2012-6-17 22:57 编辑
在问题1那里为什么不能把SetProperty 里面带有s的字符串换成a ,是不是我chang()方法里面的步骤写错了还是方法用错了?我要实现的是如:
String str ="ssksshopsszxss"------>运行chang()方法后String str ="aakaahopaazxaa"。就是把s全变成a。求解析..
public class SetProperty {
private int x;
public int y;
String str ="ssksshopsszxss";
String str1 ="ssdvbwswssyy";
public SetProperty(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return str+" : "+str1;
}
}
import java.lang.reflect.Field;
class TestReplace {// 测试
private String s = "true";// 这里同包所以用private测试可通过,property更没问题了吧
public static void main(String[] args) throws Exception {
SetProperty s = new SetProperty(2, 5);
Field fs = s.getClass().getField("y");
System.out.println(fs.get(s));
Field f = s.getClass().getDeclaredField("x");
f.setAccessible(true);
System.out.println(f.get(s));
chang(s);
System.out.println(s);
}
private static void chang(Object obj) throws Exception {
Field[] f = obj.getClass().getFields();
for (Field field : f) {
// 字节码比较用等号,不是字节码才用equals()
if (fi.getType() == String.class) {
String value1 = (String) field .get(obj);
String newvalue = value1.replace('s', 'a');//--------问题1
System.out.println("---" + newvalue);
field .set(obj, newvalue);
}
}
}
}
|