本帖最后由 张向辉 于 2012-12-27 18:01 编辑
看完张老师的视频后,实现对一个类的成员变量进行修改,我自己练习时却没成功,不知道怎么回事,请高手指导!
package cn.com;
import java.lang.reflect.Field;
public class ReflectDemo {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
ReflectDemo2 rd2 = new ReflectDemo2("private","break","exception");
replace(rd2);
System.out.println(rd2);
}
private static void replace(Object obj)throws Exception {
// TODO Auto-generated method stub
Field[] fields = obj.getClass().getFields();
for(Field field : fields)
{
if(field.getType()== String.class)
{
String oldValue = (String)field.get(obj);
String newValue = oldValue.replace('a','b');
field.set(obj, newValue);
}
}
System.out.println(obj.toString());
}
}
class ReflectDemo2
{
String str1,str2,str3;
int a =1;
public ReflectDemo2(String str1, String str2, String str3) {
super();
this.str1 = str1;
this.str2 = str2;
this.str3 = str3;
}
@Override
public String toString() {
return "ReflectDemo2 [str1=" + str1 + ", str2=" + str2 + ", str3="
+ str3 + "]";
}
}
|