使两个不可变对象相互引用的任何好方法? [英] Any nice way to make two immutable objects refer to eachother?
问题描述
接受这两个Java类:
Take these two Java classes:
class User {
final Inventory inventory;
User (Inventory inv) {
inventory = inv;
}
}
class Inventory {
final User owner;
Inventory (User own) {
owner = own;
}
}
有没有不使用反射*的方式拉这个吗?我实际上没想到会这样,但是问问并不会伤害您.
Is there any way without using reflection* to pull this off? I don't actually expect it is, but it can't hurt to ask.
更新:由于在字节码构建中有两个步骤(1.分配对象,2.调用构造函数**),可以(手写)用手写字节码或自定义编译器来做到这一点?我说的是先对两个对象执行步骤1,然后对两个对象都执行步骤2,使用步骤1的引用.当然,这样的操作会很麻烦,这部分问题是学术性的.
Update: Since in bytecode construction has two steps (1. allocate object, 2. call constructor**) could this be (ab)used to do this, with handwritten bytecode or a custom compiler? I'm talking about performing step 1 for both objects first, then step 2 for both, using references from step 1. Of course something like that would be rather cumbersome, and this part of the question is academic.
(*因为反射可能会给安全管理器带来麻烦)
(* Because reflection may give trouble with a security manager)
(**说我的知识有限)
(** Says my limited knowledge)
推荐答案
这仅在其中一个对象由另一个对象创建的情况下才能正常使用.例如,您可以将User
类更改为类似的内容(同时保持Inventory
类不变):
This can only work cleanly if one of the objects is created by the other. For example you can change your User
class to something like this (while keeping the Inventory
class unchanged):
class User {
private final Inventory inventory;
User () {
inventory = new Inventory(this);
}
}
但是,在访问Inventory
构造函数中的User
对象时需要小心,但是:它尚未完全初始化.例如,其inventory
字段仍为null
!
You need to be careful about accessing the User
object in the Inventory
constructor, however: it's not fully initialized yet. For example, its inventory
field will still be null
!
广告更新:我现在已经验证了字节码处理方法不起作用.我已经使用 Jasmin 进行了尝试,但始终无法加载
Ad Update: I've now verified that the bytecode-manipulation approach does not work. I've tried it using Jasmin and it always failed to load with a VerifyError
.
深入研究这个问题,我发现第4.10.2.4节实例初始化方法和新创建的对象.本节说明JVM如何确保仅传递初始化的对象实例.
Delving deeper into the issue, I found§ 4.10.2.4 Instance Initialization Methods and Newly Created Objects. This section explains how the JVM ensures that only initialized object instances get passed around.
这篇关于使两个不可变对象相互引用的任何好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!