Ensure method is called after all subclass constructors have finished but before object used
I am making a game and have a class that could be extended a lot, with multiple levels of classes. The subclasses may implement a wide arrange of interfaces. I have ran into an issue where calling instanceof or Class.isAssignableFrom causes significant overhead. I decided to cache possibly null instances of each interface in the object (this is a "type" object so there won't be many of them), and the fields are initialized at construction, like this:
That works fine, but then I run into the issue where the interface is just a getter, and I need the object:
But when the returned value is a variable in a subclass that is passed into constructor, it isn't initialized at that point, so it always returns null. Simple solution, right? Store the getter rather than the value. BUT the returned value has some interfaces it could implement that could also be implemented by the subclass because IValue implements IGetter and returns itself (for as many options as possible), so we do this:
and that's where the problem is. I need the value to be initialized when the value2 init code is called. However, the code should only be called once per object for efficiency, and after the last subclass constructor has finished but before any modders have the opportunity to call something on the object and mess it up. Even if I moved the container class from being a superclass to being a field in the subclass, the same issue would show up. Factory method(s) won't be feasible here.
3 Replies
⌛
This post has been reserved for your question.
Hey @The Typhothanian! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose Post
button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
Solution: Wrap the values in a field class and use supplier to get value. Then, when needed, it checks a bool for if it's been init yet. If it hasn't, then it is and sets flag to false (allowing for null values). Not perfect, but best solution I'm going to get.
Post Closed
This post has been closed by <@801145088830210129>.