package com.day2; import java.lang.reflect.Field; public class T4_ReflectReplaceString { public static void main(String[] args) { Demo demo1 = new Demo(); try { //调用该方法 reflectReplaceString(demo1); System.out.println(demo1); } catch (Exception e) { e.printStackTrace(); } } /** * 通过反射替换字符串的所有b * * @param demo * 该对象 */ public static void reflectReplaceString(Demo demo) throws Exception { // 1.得到该对象的类对象 Class c = demo.getClass(); // 2.获取所有属性对象(包括私有属性) Field[] fields = c.getDeclaredFields(); // 3.遍历 for (Field field : fields) { // 4.设置可以访问私有属性 field.setAccessible(true); // 5.获取demo的属性值 String oldVal = (String) field.get(demo); // 6.替换所有b字符为a字符 String newVal = oldVal.replace("b", "a"); // 7.设置demo的属性值为newVal field.set(demo, newVal); } } }
Demo.java
package com.day2; public class Demo { private String name = "abcdefg"; private String sex = "boy"; private String wife = "Bob"; @Override public String toString() { return "Demo [name=" + name + ", sex=" + sex + ", wife=" + wife + "]"; } }
控制台输出:
Demo [name=aacdefg, sex=aoy, wife=Boa]