- public class ReflectPoint {
- String str1 = "sontao";
- public String str2 = "foxiaotao";//此处必须是public
- public String str3 = "ou mygod";//此处必须是public
- public String toString()
- {
- return str1+" : "+str2+" : "+str3;
- }
- }
复制代码- import java.lang.reflect.Field;
- public class ReflectChangeString {
- /**
- * @param args
- */
- public static void main(String[] args)throws Exception {
- // TODO Auto-generated method stub
- ReflectPoint rpt = new ReflectPoint();
-
- Field[] fields = rpt.getClass().getFields();//得到ReflectPoint类下所有的成员变量
- for(Field field : fields)
- {
- if(field.getType()==String.class)//如果成员变量的字节码和String.class是同一个字节码,说明这是一种String类的变量
- {
- String oldValues = (String)field.get(rpt);
- String newValues = oldValues.replace('o','u');
- field.set(rpt, newValues);
- }
- }
- System.out.println(rpt);
- }
- }
复制代码 结果是:sontao : fuxiautau : uu mygud |