黑马程序员技术交流社区
标题:
将对象中字符串成员变量中的 'b' 全部换成 ‘a'
[打印本页]
作者:
fmi110
时间:
2015-9-21 12:22
标题:
将对象中字符串成员变量中的 'b' 全部换成 ‘a'
a
package test.reflect;
public class People {
String name;
String address;
public People(String name, String address) {
super();
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "People [name=" + name + ", address=" + address + "]";
}
}
复制代码
package test.reflect;
import java.lang.reflect.Field;
public class Test {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
People p = new People("hbdbsf","bbbb");
System.out.println(p);
chang(p);
System.out.println(p);
}
public static void chang(Object obj) throws Exception {
// 获取对象的字节码文件对象
Class c = obj.getClass();
// 获取成员变量的Field数组
Field[] fs = c.getDeclaredFields();
// 过滤出为String类型的Field
// 获取对象相应Field的值,并进行替换字符
for(Field f:fs){
// System.out.println("field.getClass()"+f.getClass());
if(f.getType() == String.class){//字符串变量
String oldStr = (String)f.get(obj);
String newStr = oldStr.replaceAll("b", "a");
f.set(obj, newStr);
}
}
}
}
复制代码
作者:
fmi110
时间:
2015-9-21 12:23
People [name=hbdbsf, address=bbbb]
People [name=hadasf, address=aaaa]
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2