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);
- }
- }
- }
- }
复制代码
|
|