Any nice way to make two immutable objects refer to eachother?

后端 未结 7 2473
自闭症患者
自闭症患者 2021-02-13 04:53

Take these two Java classes:

class User {
   final Inventory inventory;
   User (Inventory inv) {
       inventory = inv;
   }
}

class Inventory {
   final User         


        
7条回答
  •  [愿得一人]
    2021-02-13 05:38

    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);
       }
    }
    

    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!

    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.

提交回复
热议问题