代码如下:
class ReflectPoint {
String str1 = "zhangxiaoxiang";
String str2 = "bixiangdong";
String str3 = "heima";
public static void main(String[] args) {
}
public String toString(){
return "str1 :"+str1+" str2 :"+ str2 +" str3 :" +str3;
}
}
import java.lang.reflect.Field;
public class ReflectTest {
public static void main(String[] args) throws Exception{
ReflectPoint rp=new ReflectPoint();
replaceTest(rp) ;
System.out.println(rp);
}
private static void replaceTest(Object obj) throws Exception {
// TODO Auto-generated method stub
Field[] fields = obj.getClass().getFields();
for(Field f: fields)
{if(f.getType()==String.class)
{ String oldString =(String)f.get(obj);
String newString = oldString.replace('a', 'b');
f.set(obj, newString);
}
}
}
为什么字母改失败了,高手指点?顺便能多多介绍你对反射的理解么? |