0

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.

mark42inbound
  • 364
  • 1
  • 4
  • 19
  • 3
    You could probably make this work, but it is totally pointless because of *type erasure*. For the first part, `s.equals("B")` should do it. But for the second, Java generics are a compile time type checking mechanism. – Elliott Frisch Mar 16 '18 at 10:22
  • 1
    Something tells me that `List extends A> valueList;` may not be what you are really looking for. How are you planning to use it? – Pshemo Mar 16 '18 at 10:23
  • Possible duplicate of [Java generics - ArrayList initialization](https://stackoverflow.com/questions/4492950/java-generics-arraylist-initialization) – payloc91 Mar 16 '18 at 10:25
  • @ElliottFrisch, yes I can handle it using the 'if' case. But I want it to be as concise as possible. As the '< >' takes the class name, I want to convert the String value to pass it in the ArrayList< >. – mark42inbound Mar 16 '18 at 10:30
  • *I want to convert the String value to pass it in the ArrayList< >* You can't do that. And even if you could, it would be pointless. As I already said. Compile time checker. Not runtime. – Elliott Frisch Mar 16 '18 at 10:34

0 Answers0