本帖最后由 yinjiek 于 2013-7-29 14:29 编辑
public static void main(String[] args) throws Exception {
ChangeStringValue p1=new ChangeStringValue(3, 5);
Field fieldy=p1.getClass().getField("y");
//field不是对象身上的变量,而是类身上
System.out.println(fieldy.get(p1));
Field fieldx=p1.getClass().getDeclaredField("x");
fieldx.setAccessible(true);
System.out.println(fieldx.get(p1));
changeStringValue(p1);
System.out.println(p1);
}
private static void changeStringValue(Object obj)throws Exception {
Field [] fields=obj.getClass().getFields(); //获取class字节码文件
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 ChangeStringValue {
private int x;
public int y;
public String str1="asbbdfsf";
public String str2="gfdbgsaa";
public String str3="gfgf";
public ChangeStringValue(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return str1+":"+str2+":"+str3;
}
}
|