看了前面的那个文章之后,我就开始了解了一下sun.reflect下面的类,看到一个ReflectionFactory这个类的一个newXXXX的方法,我想如果可以给Class随便添加方法,字段的话,那么岂不是可以随便构造类型了,哈哈,感觉很好玩,于是先写了一个测试,调用newField方法,添加一个字段看看是否可以。可是遇到一些问题,现在是百思不得其解阿。贴出来,大家看看。
import java.lang.reflect.Field;
import sun.reflect.ReflectionFactory;
public class T {
public static void main(String[] arg) throws Exception {
T3 t3 = new T3();
T3 t32 = new T3();
public static void main(String[] arg) throws Exception {
T3 t3 = new T3();
T3 t32 = new T3();
ReflectionFactory rf = ReflectionFactory.getReflectionFactory();
Field f2 = rf.newField(T3.class, "newFiled", int.class, 1, 1);
System.out.println("Field Class:" + f2.getDeclaringClass());
Field f2 = rf.newField(T3.class, "newFiled", int.class, 1, 1);
System.out.println("Field Class:" + f2.getDeclaringClass());
f2.set(t3, new Integer(20));
System.out.println("t3 value:" + f2.get(t3));
System.out.println("t3 value:" + f2.get(t3));
System.out.println("t32 value:" + f2.get(t32));
Field f = t3.getClass().getField("newFiled");
f.set(t3, new Integer(20));
System.out.println(f.get(t3));
}
f.set(t3, new Integer(20));
System.out.println(f.get(t3));
}
}
class T3 {
String value;
String value;
/**
* 获得****
* @return 返回 value。
*/
public String getValue() {
return value;
}
* 获得****
* @return 返回 value。
*/
public String getValue() {
return value;
}
/**
* ****属性的方法
* @param value 要设置的 value。
*/
public void setValue(String value) {
this.value = value;
}
}
* ****属性的方法
* @param value 要设置的 value。
*/
public void setValue(String value) {
this.value = value;
}
}
现在总是抛出来一个异常,NoSuchFieldException,可是前面明明可以得到,为什么还会抛出来异常,感觉很奇怪。现在的理解是方法(Filed)已经挂上类(Class)了,可是类病没有挂上这个方法,也只能这么理解了
Field Class:class t.T3
t3 value:20
t32 value:0
java.lang.NoSuchFieldException: newFiled
at java.lang.Class.getField(Class.java:919)
at t.T.main(T.java:29)
Exception in thread "main"
t3 value:20
t32 value:0
java.lang.NoSuchFieldException: newFiled
at java.lang.Class.getField(Class.java:919)
at t.T.main(T.java:29)
Exception in thread "main"