I have a generic Factory<T>
abstract class with the createBoxedInstance()
method that returns T
instances created by createInstance()
implementations wrapped in a generic Box<T>
container.
abstract class Factory<T> { abstract T createInstance(); public final Box<T> createBoxedInstance() { return new Box<T>(createInstance()); } public final class Box<T> { public final T content; public Box(T content) { this.content = content; } } }
In some cases, I need a container like Box<S>
, where S
is the ancestor of T
Is it possible to make createBoxedInstance()
itself generic so that it returns Box<S>
instances where the caller called S
? Unfortunately, defining a function as follows does not work, since a type parameter cannot be declared using the super keyword, only used.
public final <S super T> Box<S> createBoxedInstance() { return new Box<S>(createInstance()); }
The only alternative that I see is to create all the places that need an instance of Box<S>
accept Box<? extends S>
Box<? extends S>
, which allows the container content member to be assigned S
Is there a way around this without repeatedly boxing T
instances into Box<S>
containers? (I know that I could just drop Box<T>
to Box<S>
, but I would be very, very guilty.)
source share