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

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

    The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. I suggest reading the chapter about type erasure in the Java Tutorial for more details.

    A popular solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

    class Foo {
        final Class typeParameterClass;
    
        public Foo(Class typeParameterClass) {
            this.typeParameterClass = typeParameterClass;
        }
    
        public void bar() {
            // you can access the typeParameterClass here and do whatever you like
        }
    }
    

提交回复
热议问题