天天看点

Java反射 具体需求实现案例一

//需求把某个类的里所有的String字段中的所有b字母改成c,详见changeStringValue方法
import java.lang.reflect.Field;
class ReflectPoint {
	private int x;
	public int y;
	public String str1 = "ball";
	public String str2 = "body";
	public String str3 = "sun";
	public String str4 = "color";
	public ReflectPoint(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	
	@Override
	public String toString() {
		return "ReflectPoint [x=" + x + ", y=" + y + ", str1=" + str1
				+ ", str2=" + str2 + ", str3=" + str3 + ", str4=" + str4 + "]";
	}
	
}
public class Test {
	public static void main(String[] args) throws Exception {
		ReflectPoint pt = new ReflectPoint(3, 5);
		changeStringValue(pt);
		System.out.println(pt.toString());
	}
	private static void changeStringValue(Object obj) throws Exception {
		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', 'c');
				field.set(obj, newValue);
			}
		}
	}

}
/*输出
true
true
 */