Generics List with string classname

2019-09-10 10:16发布

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.

标签: java generics
2条回答
姐就是有狂的资本
2楼-- · 2019-09-10 10:34

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-09-10 10:40

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 a List<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 and Integer 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 put Foo instances in it during one run, and Bar instances during another.

查看更多
登录 后发表回答