I am trying to debug a Java application that is relying on Reflection. Right now the error I get is the following:
java.lang.IllegalArgumentException: Can not set int field DataStructures.StackAr.topOfStack to java.lang.Integer
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:37)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.getInt(UnsafeIntegerFieldAccessorImpl.java:38)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.get(UnsafeIntegerFieldAccessorImpl.java:18)
at java.lang.reflect.Field.get(Field.java:358)
THe last lines of the application running are:
Field f = classUnderTest.getDeclaredField(processFieldName(var));
f.setAccessible(true);
Long value = (Long) f.get(runtimeInstance);
The error message is a bit misleading and I am not sure why it is mentioning a set operation whereas I am trying to preform a get.
I am suspecting that the runtimeInstance is not an object of the expected class. But that error message is throwing me away.
Has anyone encountered this issue before? Any clues?
PS1: The exact line causing the exception is this one:
Long value = (Long) f.get(runtimeInstance);
PS2: processFieldName(var) processes the correct name of the field, i.e. it removes some artefacts from a string with the field name like this. and so on.
From the source of those accessors it seems that the class declaring the field is not assignable from the
runtimeInstance‘s class:fieldseems to be the field you want to get from the instance,paramObjectis yourruntimeInstance.Thus, if the declaring class of the field isn’t the class or a super class of the paramObject you’d get that message.
Any chance your
paramObjectis anIntegerhere?Edit: here’s some source code from OpenJDK (should be similar to Oracle’s), to explain the message:
Taking your message
java.lang.IllegalArgumentException: Can not set int field DataStructures.StackAr.topOfStack to java.lang.Integerwe find that:inttopOfStackin classDataStructures.StackArattemptedTypeisjava.lang.IntegerSince
attemptedTypeis the type of yourruntimeInstanceI suspectclassUnderTestisDataStructures.StackArwhereasruntimeInstanceis of typejava.lang.Integer.