是否可以将类型保存在变量中,
以便实例化这种类型的列表?
//something like that
Type type = Boolean;
List<type> list = new List<type>();
list.add(true);
For the first requirement, you are looking for Class
:
Class type = Boolean.class;
However, I don't think the seconds requirement is feasible, since generic types only exist at compile time:
List<type> list = new List<type>(); // invalid code
You can, however, work with List<Object>
. It will accept Boolean
objects. Whether this will buy you anything untlimately depends on your use case.
Generic is a compile time feature, not run time, so you cannot use variable to determine the generic type, even using NPE's note (using Class
) will not compile:
Class<?> type = Boolean.class;
// can't do that...
List<type> list = new List<type>();
list.add(true);
在第二种情况下,当类型未知时,为什么要使用泛型?您可以更好地使用非泛型数组列表(在 jdk 5 之前使用)。
List a = new ArrayList();
a.add(object);
更高版本仍然支持这种样式,甚至泛型样式在编译后也会转换为这种形式。您将在上面的代码中收到可以禁止的警告。