Is there any way to do the following in Java?
I want to initialize an ArrayList
based on a string value. Here the string value will definitely be one of the subclass names. I'm aware of using the Class< T >
type to initialize an ArrayList
of any type. But the catch is, the initialized list should be of type List< ? extends ParentClass >
. Is there a way to use the Class< T >
along with the < ? extends ParentClass >
?
class A{
String s;
}
class B extends A{
String b;
}
class D extends A{
String d;
}
class C{
List<? extends A> valueList;
public C(String s){
//The string s decides if the list is of type B or type C.
if(type B){
this.valueList = new ArrayList<type B>();
}
else{
this.valueList = new ArrayList<type D>();
}
}
}
EDIT: As the '< >' takes the class name, I want to convert the String value to pass it in the ArrayList< >. I'm not sure to what type should I convert the String value to.