java.lang.reflect.Field#slot
是否保存了字段在源文件中声明的顺序号?
我知道它是私有的,不应该使用它之类的,但无论如何......
java.lang.reflect.Field#slot
是否保存了字段在源文件中声明的顺序号?
我知道它是私有的,不应该使用它之类的,但无论如何......
Field.slot
的含义是实现定义的。在HotSpot JVM中,它包含给定类的VM内部字段数组的索引。当创建Field
对象时,slot
字段在JVM运行时被设置。请参见reflection.cpp。
这个索引不一定与Java源文件中字段的顺序匹配。它也不相关于字段从对象头的偏移量。最好不要对slot
的含义进行任何假设。关键的意义在于允许JVM快速地将java.lang.reflect.Field
对象映射到Metaspace中的内部字段表示。
该字段由JVM分配(我在Java代码中找不到任何设置它的内容),其中包含类中方法的某种索引。一个简单的程序可以告诉您一些关于它的信息:
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);
}
}
}
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