java - 继承会改变使用 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 类的好奇而提出的。如果这个问题太宽泛或不适合这里,请在评论中告诉我以改进或删除问题。
解决方案
子类通常共享父类的结构,可能在所有父字段之后添加更多字段。这不是 Java 特有的——其他语言(例如 C++)中的继承以类似的方式实现。这使得无需动态类型检查就可以有效地将子类用作父类的实例。
因此,该字段的偏移量在父类及其所有后代类中将保持不变。JVM不需要这样做,但是我知道的所有合理的实现都遵循这个规则。
严格来说,Unsafe
class 已经是特定 JVM 的一个实现细节,所以所有关于的声明Unsafe
都是特定于 VM 的定义。
推荐阅读
- powershell - 如何在powershell中添加引号和逗号
- jquery - 未捕获的类型错误:无法在 DATATABLE HTML5 PDF 导出中读取未定义的属性“正文”
- java - 如何在 Java 中模拟 fork 和管道?
- angular - 角度验证错误没有显示在 gui 上?
- javascript - redux 操作中的 fetch 什么都不做
- java - 有没有办法改变 Gif 速度
- spring-boot - 无法更改rabbitmq默认用户
- python - SyntaxError:无法分配给函数调用和循环
- bash - 使用 find 将多个 java 文件传递给 javac
- julia - 计算概率的函数问题