利用反射将字段为String类型的成员变量中的字符串中的i改为Q

来源:互联网 发布:com.tw 域名注册 编辑:程序博客网 时间:2024/05/29 03:24
import java.lang.reflect.Field;class StrTest{public String name="fdsfii";public String address="rwrwi";public String country="fref";}public class RefExample {public static void main(String [] args) throws Exception{Class cl=StrTest.class;Field []fields=cl.getFields();StrTest str=new StrTest();for(Field field:fields){if(field.getType()==String.class){String oldValue=(String)field.get(str);String newValue=oldValue.replace('i', 'Q');field.set(str, newValue);}}System.out.println(str.name);System.out.println(str.address);System.out.println(str.country);}}

原创粉丝点击