黑马程序员技术交流社区
标题:
反射的代码有错误
[打印本页]
作者:
黑马张伟
时间:
2011-12-26 19:11
标题:
反射的代码有错误
本帖最后由 黑马张伟 于 2011-12-27 08:42 编辑
package reflect;
import java.lang.reflect.Field;
public class ReflectTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt1=new ReflectPoint();
changeStringValue(pt1);
System.out.println(pt1);
}
private static void changeStringValue(Object obj) throws Exception{
Field [] fileds=obj.getClass().getFields();
for(Field filed :fileds){
if(filed.getType()==String.class){
String oldValue =(String)filed.get(obj);
String newValue =oldValue.replace('b','a');
filed.set(obj,newValue);
}
}
}
}
另一个class
package reflect;
public class ReflectPoint {
public String str1 ="sdfasdfsdfasds";
public String str2 = "sdfasdgassdg";
public String str3 ="vd;foijdf";
public ReflectPoint() {
super();
this.str1 = str1;
this.str2 = str2;
}
public String toString(){
return str1+":"+str2+":"+str3;
}
}
没有调用成功ReflectPoint pt1=new ReflectPoint();这段代码有问题不知如何解决
作者:
吴上储
时间:
2011-12-26 19:31
代码没错 你str1 str2 str3 里面有b么?我怎么没看见啊!
作者:
刘海涛
时间:
2011-12-26 19:42
楼主代码毫无问题:
看下面代码:
package reflect;
public class ReflectPoint {
public String str1 = "ab1";
public String str2 = "ab2";
public String str3 = "ab3";
public String toString() {
return str1 + ":" + str2 + ":" + str3;
}
}
package reflect;
import java.lang.reflect.Field;
public class ReflectTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt1 = new ReflectPoint();
changeStringValue(pt1);
System.out.println(pt1);
}
private static void changeStringValue(Object obj) throws Exception {
Field[] fileds = obj.getClass().getFields();
for (Field filed : fileds) {
if (filed.getType() == String.class) {
String oldValue = (String) filed.get(obj);
String newValue = oldValue.replace('b', 'a');
filed.set(obj, newValue);
}
}
}
}
复制代码
输出:aa1:aa2:aa3
下面代码在程序当中是多余的:
public ReflectPoint() {
super();
this.str1 = str1;
this.str2 = str2;
}
复制代码
作者:
颜宗茂
时间:
2011-12-26 20:13
public ReflectPoint() {
super();
this.str1 = str1;
this.str2 = str2;
}
这段代码是错误的,你都没传参数str1和str2,怎么给this.str1和str2赋值呢,像上面所说,直接去掉代码就会有默认的构造方法,也是可以的。要不ReflectPoint pt1=new ReflectPoint()是不行的。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2