import java.lang.reflect.Field;
public class TestMain {
public void setName(Object obj, String name, Object o){
try {
Field f = obj.getClass().getDeclaredField(name);
f = obj.getClass().getDeclaredField(name);
System.out.println(f);
f.setAccessible(true);
try {
f.set(obj,o);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
TestMain c = new TestMain();
c.setName(c,"TestMain.java", c);
System.out.println(c);
}
}
这段代码编译没有错,但是运行就会报一下错误,什么原因呢?
java.lang.NoSuchFieldException: TestMain.java
at java.lang.Class.getDeclaredField(Class.java:1882)
at com.itcast.test.TestMain.setName(TestMain.java:9)
at com.itcast.test.TestMain.main(TestMain.java:33)
com.itcast.test.TestMain@150bd4d
|