- import java.lang.reflect.Field;
- public class ReflectTest1 {
- public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
- ReflectPoint rp = new ReflectPoint(3, 5);
- changeStringValue(rp);
- System.out.println(rp);
- }
- public static void changeStringValue(Object obj) throws IllegalArgumentException, IllegalAccessException {
- Field[] fields = obj.getClass().getFields();
- for(Field f : fields){
- if(f.getType() == String.class){
- String oldValue = (String)f.get(obj);
- String newValue = oldValue.replace('b', 'a');
- f.set(obj, newValue);
- }
- }
- }
- }
- public class ReflectPoint {
- private int x;
- public int y;
- String str1 = "banana";
- String str2 = "bite";
- String str3 = "ball";
- String str4 = "big";
- public ReflectPoint(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
-
- @Override
- public String toString(){
- return str1+":"+str2+":"+str3+":"+str4;
- }
- }
复制代码 将任意一个对象中的所有String类型的成员变量所对应的字符串内容中的"b"改成"a"。为什么没有替换成功? |