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

前端 未结 22 1340
猫巷女王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:48

    A standard approach/workaround/solution is to add a class object to the constructor(s), like:

     public class Foo {
    
        private Class type;
        public Foo(Class type) {
          this.type = type;
        }
    
        public Class getType() {
          return type;
        }
    
        public T newInstance() {
          return type.newInstance();
        }
     }
    

提交回复
热议问题