编程实例:将任意一个对象中的所有String类型的成员变量所对应的字符串内容中的“b”改为“a”。
实现代码:
ReflectTest.java文件代码:
package cn.yzx.day1;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class ReflectTest {
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
ReflectPoint pt1 = new ReflectPoint(3, 5);
changeStringValue(pt1);
System.out.println(pt1);
}
private static void changeStringValue(Object obj)throws Exception {
// TODO Auto-generated method stub
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);
}
}
}
}
ReflectPoint.java文件代码:
package cn.yzx.day1;
public class ReflectPoint {
private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcast";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString()
{
return str1 + ":" + str2 + ":" + str3;
}
}
运行结果: