黑马程序员技术交流社区
标题:
求教一个反射问题 大神速进
[打印本页]
作者:
kira
时间:
2014-2-24 15:55
标题:
求教一个反射问题 大神速进
需求是利用反射的思想 将字符串中的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
求助这是怎么回事 我该怎么改
作者:
kira
时间:
2014-2-24 16:05
好吧 我找到错误了 set方法传参错了
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(o, 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;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2