需求是利用反射的思想 将字符串中的b变成a
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- public class ConDemo {
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- Reflectpo rp = new Reflectpo(3,5);
- changeStringFun(rp);
- System.out.println(rp);
- }
- private static void changeStringFun(Object o) throws Exception{//这里传入Object
- //得到字段
- Field[] f = o.getClass().getFields();
- //对字段进行遍历
- for(Field ff:f){
-
- //判断是不是String
- if(ff.getType()==String.class){//字节码用等号比 得到字段
- String olds = (String)ff.get(o);
- String news = olds.replace('b', 'a');
- //修改字段
- ff.set(olds, news);
- }
-
- }
-
- }
- }
- class Reflectpo{//创建一个类
- private int x,y;
- public String s1 ="ball";//新加两个成员变量
- public String s2 ="car";
- Reflectpo(int x ,int y){
- super();
- this.x=x;
- this.y=y;
- }
- public String toString(){
-
- return s1+"::"+s2;
- }
- }
复制代码 我的代码 结果却发现即使覆盖了toString方法之后
还是 报了个异常
Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.String field com.XXX.Reflectpo.s1 to java.lang.String
求助这是怎么回事 我该怎么改
|