什么是java.lang.reflect.Field#slot?

4

java.lang.reflect.Field#slot是否保存了字段在源文件中声明的顺序号?
我知道它是私有的,不应该使用它之类的,但无论如何......

2个回答

3
Field.slot的含义是实现定义的。在HotSpot JVM中,它包含给定类的VM内部字段数组的索引。当创建Field对象时,slot字段在JVM运行时被设置。请参见reflection.cpp

这个索引不一定与Java源文件中字段的顺序匹配。它也不相关于字段从对象头的偏移量。最好不要对slot的含义进行任何假设。关键的意义在于允许JVM快速地将java.lang.reflect.Field对象映射到Metaspace中的内部字段表示。


1

该字段由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

子类中的方法似乎具有最低的索引,其次是Object类中的方法,有些索引不是唯一的(尽管它们可能在声明的类中是唯一的)。因此,我不想依赖该值做任何事情。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接