带字符串类名的泛型列表 [英] Generics List with string classname
问题描述
如何用字符串中的类名声明一个列表。例如:我有一个className变量和一个类的名字。我需要使用className变量中的类型创建List。
String className =com.foo.Foo;
有可能有一个列表结果是相同的
列表< Foo> fooList = new ArrayList< Foo>();
不知道声明时的类型。
List< Bar>
。 你不能那样做;包括泛型在内的类型检查是在编译时完成的。这与你在一次运行中不能有一个类型为 String
的变量以及另一次运行时的 Integer
类似。 / p>
如果您希望能够在运行时选择不同类型,泛型类型参数必须是您可能选择的所有类型的超类型。例如,你可以有一个 List< Object>
,并且在一次运行中放入 Foo
code> Bar 实例。
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.
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.
这篇关于带字符串类名的泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!