How do I get a class instance of generic type T?

前端 未结 22 1254
猫巷女王i
猫巷女王i 2020-11-21 11:03

I have a generics class, Foo. In a method of Foo, I want to get the class instance of type T, but I just can\'t call T.

22条回答
  •  礼貌的吻别
    2020-11-21 11:44

    A better route than the Class the others suggested is to pass in an object that can do what you would have done with the Class, e.g., create a new instance.

    interface Factory {
      T apply();
    }
    
     void List make10(Factory factory) {
      List result = new ArrayList();
      for (int a = 0; a < 10; a++)
        result.add(factory.apply());
      return result;
    }
    
    class FooFactory implements Factory> {
      public Foo apply() {
        return new Foo();
      }
    }
    
    List> foos = make10(new FooFactory());
    

提交回复
热议问题