-------android培训、java培训、期待与您交流! ----------
需求:通过反射的方式把某个类的String 类型的变量的值中的 ‘a’改成‘b’
<span style="font-size:18px;"><span style="font-size:18px;">package test;
public class ReflectPoint {
private int x;
public int y;
public String str1 = "basketball";
public String str2 = "envriement";
public String str3 = "bbbcccbbbbbbbbb";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString()
{
return str1+"::"+str2+"::"+str3;
}
}
</span></span>
<span style="font-size:18px;"><span style="font-size:18px;">package test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.*;
public class ReflaectTest {
public static void main(String[] args ) throws Exception {
ReflectPoint pt1 = new ReflectPoint(3,5);
Field fieldy = pt1.getClass().getField("y");
System.out.println(fieldy.get(pt1));
Field fieldx = pt1.getClass().getDeclaredField("x");
fieldx.setAccessible(true);
System.out.println(fieldx.get(pt1));
changeStringValue(pt1);
System.out.println(pt1);
}
private static void changeStringValue(Object obj) throws Exception {
Field [] fields = obj.getClass().getFields();
for (Field field : fields) {
//判断字段类型是否为String类型,如果是则替换
if (field.getType()== String.class) {
String oldValue = (String)field.get(obj);
String newValue = oldValue.replace('b', 'a');
field.set(obj, newValue);
}
}
}
}</span></span>