当我使用java reflection api
时,我遇到了这个异常java.lang.IllegalArgumentException
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:37)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:18)
at java.lang.reflect.Field.get(Field.java:357)
代码:
Field fieldlist[] = TestValue.class.getDeclaredFields();
String result="";
try {
for (int i = 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
result += "name = " + fld.getName() + "\n";
fld.setAccessible(true);
result += "value = " + fld.get(this)+ "\n";
System.out.println("Result----->"+result);
}
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
答案 0 :(得分:3)
只是猜测但是,......字段的类型与您传递的对象不同。
编辑:您正在获取TestClass的字段并使用它们来查找当前对象。
相反,您可以编写以下内容来查找 this
的类字段Field fieldlist[] = this.getClass().getDeclaredFields();