Reputation: 805
Does java.lang.reflect.Field#slot
hold a sequence number in the order how fields were declared in the source file?
I know its private and I should not use it and stuff but anyway...
Upvotes: 5
Views: 1244
Reputation: 98550
Field.slot
meaning is implementation defined. In HotSpot JVM it contains the index into the VM's internal field array for the given class. slot
field is set inside JVM runtime when a Field
object is created, see reflection.cpp.
This index does not necessarily match the order of the fields in Java source file. It is neither related to the offset of the field from the object header. It is better not to make any assumptions about the meaning of slot
. The key meaning is to allow JVM to quickly map a java.lang.reflect.Field
object to the internal Field representation in Metaspace.
Upvotes: 3
Reputation: 8841
The field is allocated by the JVM (I can't find anything setting it in Java code) and contains some kind of index of the method in the class. A simple program can tell you a bit about it:
package slot;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class SlotTester {
public void method1() {
}
public void method2() {
}
public static void method3() {
}
public void method4() {
}
public static void main(String[] args) throws Exception {
SlotTester s = new SlotTester();
Method[] methods = s.getClass().getMethods();
for (Method method : methods) {
Field f = method.getClass().getDeclaredField("slot");
f.setAccessible(true);
Integer slot = (Integer) f.get(method);
System.out.println(method.getName() + " " + slot);
}
}
}
Displays:
main 1
method1 2
method2 3
method3 4
method4 5
wait 3
wait 4
wait 5
equals 6
toString 7
hashCode 8
getClass 9
notify 12
notifyAll 13
So the methods in the subclass appear to have the lowest indices, followed by those in Object, and some indices are not unique (though perhaps they are within the declared class).
So I would not like to rely on the value for anything.
Upvotes: 1