- import java.lang.reflect.*;
- class FieldTest
- {
- public static void main(String[] args) throws Exception
- {
- FieldDemo fd = new FieldDemo();
- replacetest(fd);
- System.out.println(fd);
- }
- private static void replacetest(Object obj)throws Exception{
- Field[] fields = obj.getClass().getFields();
- for(Field field : fields){
- if(field.getType() == String.class){
- String oldvalue = (String)field.get(obj);
- String newvalue = oldvalue.replace('b','a');
- field.set(obj,newvalue);
- }
- }
-
- }
- }
- class FieldDemo
- {
- String str1 = "ball";
- String str2 = "basketball";
- String str3 = "itcast";
- public String toString(){
- return "str1"+"-->"+str1+"\n"+"str2"+"-->"+str2+"\n"+"str3"+"-->"+str3+"\n";
- }
- }
复制代码 |