给定一个Class对象,我如何创建它引用的类类型列表的实例

时间:2018-11-27 18:27:53

标签: java generics

这将很难解释,但我将尝试使其尽可能简单。 可以说我有一个名为Car的对象,并且我有一个接收以下内容的函数:

public void foo(Class<Car> type){
    // I want to create a list of this type, do something like this
    List<type> list = new List<type>
    // I know its not the way to do it but is there any way to do something like this
长话短说,我想创建一个列表,该列表将是汽车列表 可以给定Class对象吗?

1 个答案:

答案 0 :(得分:2)

由于您提到您不知道实际类型(在示例中为Car),因此我假设您正在使用泛型。

  public <T> void foo(Class<T> t) {
    List<T> list = new ArrayList<T>();
  }

这是一个通用方法,因此您可以使用Class对象中的相同类型参数来创建列表。不过,我不确定您为什么要这么做。如果您已经具有用于Class对象的type参数,那么您实际上就不需要Class对象来创建列表。您可以只做List<T> list = new ArrayList<T>()

相关问题