本帖最后由 sunhaodi 于 2012-6-23 22:38 编辑
package day01;
import java.lang.reflect.Field;
public class ReflectDemo {
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Person p = new Person(3,4);
//Field filedx = p.getClass().getField("x");
//System.out.println(filedx.get(p)); //这个代码我和张孝祥老师写的一样, 为什么运行不出来会报错啊
// Field filedy= p.getClass().getDeclaredField("y");
// filedy.setAccessible(true);
// System.out.println(filedy.get(p));
getTest(p);
System.out.println(p);
}
public static void getTest(Object obj) throws IllegalArgumentException, IllegalAccessException{ //这个方法把aaaaa改成bbbbbbb 为什么弄完了也没改啊还是aaaaaaaaaa
Field[] fileds=obj.getClass().getFields();
for (Field field : fileds) {
if(field.getType()==String.class){
String s =(String) field.get(obj);
String value=s.replace('a','b');
field.set(obj, value);
}
}
}
}
class Person{
private int x;
private int y;
private String str1 = "aaaaaaa";
private String str2 ="ddddddd";
public Person(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return str1+".............."+str2;
}
}
代码和老师的一样啊,郁闷了 |
|