How do I declare a list with the class name in a string. For eg: I have a className variable with the name of a class. I need to create List with the type in the className variable.
String className ="com.foo.Foo";
Is it possible to have a list that is having the same result of
List<Foo> fooList = new ArrayList<Foo>();
without knowing the type at the time of declaration.
Multipart question "How do I declare a list with the class name in a string": you can not declare like in that way. for "Is it possible to have a list that is having the same result of": you can create something like "List fooList = new ArrayList();" But you should be take care of the type casting while accessing the fooList.
It's not entirely clear, but it sounds like you're talking about making a list whose generic type parameter is determined at runtime, e.g. it could be a
List<Foo>
during one run and aList<Bar>
during another.You can't do that; type-checking, including generics, is done at compile time. It's the same reason you can't have a variable whose type is
String
during one run andInteger
during another.If you want to be able to choose different types at runtime, the generic type parameter has to be a supertype of all the types you might choose. For example, you could have a
List<Object>
, and putFoo
instances in it during one run, andBar
instances during another.