本帖最后由 严学韦 于 2012-9-11 10:32 编辑
下面这段关于反射的代码,我已经写成跟张老师的一模一样的了,可是在台式机上运行结果正常,在笔记本上就不行了
package packge1;
public class ReflectPoint {
public int x;
public int y;
public String str1 = "ball";
public String str2 = "base";
public String str3 = "bpple";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
public String toString(){
return str1 + ":"+str2 +":"+ str3;
}
}
------------------------------------------------------------
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class ReflectTest {
public static void main(String[] args) throws Exception{
ReflectPoint pt1 = new ReflectPoint(3,5);
changeStringValue(pt1);
System.out.println(pt1);
}
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);
}
}
}
}
在台式机上的时候运行结果:aall:aase:apple
在笔记本上运行结果不正确:bbll:base:bpple
折腾俺半天,就是不行,也不报异常,这是为什么呀
|
|