首页 > 解决方案 > 继承会改变使用 Unsafe 类获得的字段的偏移量吗?还是取决于具体的虚拟机实现?

问题描述

当我试图理解“Unsafe.objectFieldOffset”时,我对代码中的注释感到困惑。

// Any given field will always have the same offset, and no two distinct fields of the same class will ever have the same offset.

这是否意味着我在抽象类中获得了一个字段的偏移量,这个字段在实现类中仍然具有相同的偏移量,因为它们是同一个字段?

以下是示例代码,只是为了说明问题:

public abstract class Parent {
    protected Object value;
}
// Because the question is asked for any implementation class, only a simple example is given
public class Son extends Parent {
    public Son(Object value) {
        this.value = value;
    }

    Object useless_1;
    Object useless_2;
    Object useless_3;
    Object useless_4;
}

public class ParentTool {
    protected static final long offset;
    private static final Unsafe unsafe;

    // Initialize static fields
    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
            offset = unsafe.objectFieldOffset(Parent.class.getDeclaredField("value"));
        } catch (Throwable e) {
            throw new Error(e);
        }
    }

    // Hope this method can get and set the fields correctly
    protected static Object getAndSetValue(Parent parent, Object newValue) {
        return unsafe.getAndSetObject(parent, offset, newValue);
    }
}

用于测试的启动类如下

public class Program {
    public static void main(String[] args) {
        Son son = new Son("hello");
        Object value;

        value = ParentTool.getAndSetValue(son, "world");
        System.out.println(value == "hello"); // true
        value = ParentTool.getAndSetValue(son, "test");
        System.out.println(value == "world"); // true
    }
}

运行结果符合预期

true
true

“getAndSetValue”是否总是适用于任何继承 Parent 的类?这是否取决于具体的虚拟机实现?

我使用的JDK版本如下图

OpenJDK 64-Bit Server VM Corretto-8.222.10.3

这个问题是出于对 Unsafe 类的好奇而提出的。如果这个问题太宽泛或不适合这里,请在评论中告诉我以改进或删除问题。

标签: javajvm

解决方案


子类通常共享父类的结构,可能在所有父字段之后添加更多字段。这不是 Java 特有的——其他语言(例如 C++)中的继承以类似的方式实现。这使得无需动态类型检查就可以有效地将子类用作父类的实例。

因此,该字段的偏移量在父类及其所有后代类中将保持不变。JVM不需要这样做,但是我知道的所有合理的实现都遵循这个规则。

严格来说,Unsafeclass 已经是特定 JVM 的一个实现细节,所以所有关于的声明Unsafe都是特定于 VM 的定义。


推荐阅读