Deriving type from Generic classes
-
26-06-2021 - |
Question
I have a generic class which takes two type parameters:
public class MyGenericClass<T, S> {
private List<T> myList;
private List<S> mySecondList;
//...
public void addToFirstList(T e) {
myList.add(e);
}
//...
}
I want to be able to specify concrete types for these two parameters upon creating an instance of the class within a factory and then to be able to derive these types from within the rest of my code.
For instance, if I have the code:
public class AccessFactory {
public static MyGenericClass<Integer, Float> getInst() {
return new MyGenericClass<Integer, Float>();;
}
}
public class UsingFactoryClass {
private MyGenericClass access;
...
public foo() {
access = AccessFactory.getInst();
}
}
I'd like to be able to derive that the MyGenericClass
instance access
in the UsingFactoryClass
class uses the parameters Integer
and Float
.
Is it possible to do this without having to contend with type safety warnings everywhere?
Solution
Declare it as:
private MyGenericClass<Integer, Float> access;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow