Making a API for internal use, I need some Java abstraction and I don't know how to do it.
- There is an Interface A with derived interfaces.
- Let's say one of the extended interfaces of A is called B.
- And let's say there is an class C implementing B.
I have a Factory/Pool class F from which I want to get a list of instances (or set or similar collection). What I want is basically this:
List<B> instances = F.getAllSuitableInstances(parameters);
Get me all the instances specified by my parameters as a collection of B.
First attempt was with this function signature
public List<A> getAllSuitableInstances(parameters);
but when I try to cast the resulting List to a List for use, I get told "incompatible types" - even though B is derived from A.
So I tried what the java libraries do:
public <T> List<T> getAllSuitableInstances(parameters, T);
and try calling that with B as second parameter. But that doesn't work either, since T has to be supplied as an instance for some reason, and interfaces cannot have instances.
I know I could use <?>
with casting but I'd like to make this as typesafe as possible.
So, what is the (best) way to get this done?