Reputation: 486
getDeclaredFields[0].getType() is returning only the compile time class info. I have following code, where java.lang.reflect.Field
's type is expected with actual type. This field is passed to Unsafe.objectFieldOffset(f)
public class Wrapper {
public Object field1;
//getters and setters for field1 and constructor
}
class SomeClass {
}
Wrapper wrapper = new Wrapper();
wrapper.field1 = new SomeClass();
System.out.println(wrapper.getClass().getDeclaredFields[0].getType());
Even though object is available with wrapper.field1.getClass(), Unsafe.objectFieldOffset(f)
requires Field instance so wrapper.getClass().getDeclaredFields[0].getType()
needs to return actual type which SomeClass instead of Object. Is there anyway I can override that behaviour ?
To rephrase, Is there anyway to use Unsafe.objectFieldOffset(f)
with Runtime type info?
Upvotes: 1
Views: 357
Reputation: 2313
Unfortunately, this will not be possible. getDeclaredFields()
will do exactly that - return fields with compile-time information. You will have to retrieve the runtime type using field1.getClass()
.
Edit: You may also indirectly retrieve the class, using wrapper.getType().getDeclaredFields[0].get(wrapper).getClass();
Upvotes: 2