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.
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)
This can only work cleanly if one of the objects is created by the other. For example you can change your
Userclass to something like this (while keeping theInventoryclass unchanged):You need to be careful about accessing the
Userobject in theInventoryconstructor, however: it’s not fully initialized yet. For example, itsinventoryfield will still benull!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.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.