ReflectPoint.java
package com.belmeng.test;
public class ReflectPoint
{
private int x;
private int y;
public String str1="abc";
public String str2="aef";
public String str3="ahi";
public ReflectPoint()
{
}
public ReflectPoint(int x, int y)
{
this.x = x;
this.y = y;
}
@Override
public String toString()
{
// TODO Auto-generated method stub
return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="
+ str3 + ", x=" + x + ", y=" + y + "]";
}
}
ReflectTest.java
package com.belmeng.test;
import java.lang.reflect.Field;
public class ReflectTest
{
public static void main(String[] args) throws Exception
{
ReflectPoint point=new ReflectPoint(3, 5);
System.out.println("之前:"+point);
changeValue(point);
System.out.println("之前:"+point);
}
private static void changeValue(Object obj) throws Exception{
Field[] fields=obj.getClass().getFields();
for(Field f:fields)
{
if(f.getType()==String.class)
{
String value=(String)f.get(obj);
String newValue=value.replace("a", "b");
f.set(obj, newValue);
}
}
}
}