开发者

i got this exception when i am using java reflection api

i got开发者_开发问答 this exception when i am using 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)

Code:

    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();
    }


Just guessing but, ... the Field is for a type which is not the same as the object you are passing.

EDIT: You are getting the fields of TestClass and using them to lookup the current object.

Instead you can write the following to lookup the field of the class for this

Field fieldlist[] = this.getClass().getDeclaredFields();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜