黑马程序员技术交流社区

标题: 将对象中字符串成员变量中的 'b' 全部换成 ‘a' [打印本页]

作者: fmi110    时间: 2015-9-21 12:22
标题: 将对象中字符串成员变量中的 'b' 全部换成 ‘a'
a
  1. package test.reflect;

  2. public class People {
  3.         String name;
  4.         String address;
  5.         public People(String name, String address) {
  6.                 super();
  7.                 this.name = name;
  8.                 this.address = address;
  9.         }
  10.         @Override
  11.         public String toString() {
  12.                 return "People [name=" + name + ", address=" + address + "]";
  13.         }
  14.        
  15. }
复制代码
  1. package test.reflect;

  2. import java.lang.reflect.Field;

  3. public class Test {

  4.         /**
  5.          * @param args
  6.          * @throws Exception
  7.          */
  8.         public static void main(String[] args) throws Exception {
  9.                 People p = new People("hbdbsf","bbbb");
  10.                 System.out.println(p);
  11.                 chang(p);
  12.                 System.out.println(p);
  13.         }
  14.         public static void chang(Object obj) throws  Exception {
  15.                 // 获取对象的字节码文件对象
  16.                 Class c = obj.getClass();
  17.                 // 获取成员变量的Field数组
  18.                 Field[] fs = c.getDeclaredFields();
  19.                 // 过滤出为String类型的Field
  20.                 // 获取对象相应Field的值,并进行替换字符
  21.                 for(Field f:fs){
  22. //                        System.out.println("field.getClass()"+f.getClass());
  23.                         if(f.getType() == String.class){//字符串变量
  24.                                 String oldStr = (String)f.get(obj);
  25.                                 String newStr = oldStr.replaceAll("b", "a");
  26.                                 f.set(obj, newStr);
  27.                         }
  28.                 }
  29.         }
  30. }
复制代码




作者: fmi110    时间: 2015-9-21 12:23
  1. People [name=hbdbsf, address=bbbb]
  2. People [name=hadasf, address=aaaa]
复制代码






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2