I have seen advice that a Supplier can be used to create an instance of a parametrized class.
E.g. Here: "Instantiating object of type parameter" or here: "Create instance of generic type in Java?"
How to create the Supplier seems clear from the linked answers:
// Example of creating objects in linked answers
MyClass<StringBuilder> it = new MyClass<>(StringBuilder::new);
SomeContainer<String> stringContainer = new SomeContainer<>(String::new);
but how to use it for a recursive set of classes based on generic container doesn't seem to be clear.
My problem is that this Supplier methods itself has to be called as a parameter of the constructor for each recursive class. Example:
class SetOf<E> {
// Supplier-based code from SO Q #75175
private Supplier<E> supplier;
SetOf(Supplier<E> supplier) { this.supplier = supplier; }
createE() { return supplier.get(); }
addToContainer(key) {
E value = createE(); // I assume that's how it's used?
this.add(key, value);
}
}
The problem here is that if we are building container of containers thusly:
class SetOfThings extends SetOf<Thing> {}
class SetOfSetsOfThings extends SetOf<SetOfThings> {}
class SetOfSetOfSetsOfThings extends SetOf<SetOfSetOfThings> {}
SetOf<SetOfSetOfSetOfThings> root = new SetOf<>(SetOfSetOfThings::new);
So, what we are passing to the Supplier of outer class (SetOfSetOfSetOfThings) is the reference to constructor of inner class (SetOfSetOfThings) - BUT, when that SetOfSetOfThings()
constructor will be called, it will be called with no parameters, meaning that there will be NO supplier for SetOfThings set in the SetOfSetOfThings
object! (which means we can never create SetOfThings objects).
I suppose we can fix this 3-level chain somehow, by using Lambda syntax and passing a parameter (with value of SetOfThings::new) to SetOfSetOfThings::new in turn. But this only works because our chain is 3 levels deep - what if we have to instantiate 4-level deep chain with root class being SetOfSetOfSetsOfSetsOfThings?
This question is a very narrow Function/Supplier specific version of my more generic earlier question here (where comments pointed to both Supplier as an idea, and the linked answer showing how to use a supplier in general - neither of which work easily in case of recursive class hierarchy).