Create instance of generic type in Java?

后端 未结 27 3104
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 06:14

Is it possible to create an instance of a generic type in Java? I\'m thinking based on what I\'ve seen that the answer is no (due to type erasure), but

27条回答
  •  野的像风
    2020-11-21 07:02

    You can do this now and it doesn't require a bunch of reflection code.

    import com.google.common.reflect.TypeToken;
    
    public class Q26289147
    {
        public static void main(final String[] args) throws IllegalAccessException, InstantiationException
        {
            final StrawManParameterizedClass smpc = new StrawManParameterizedClass() {};
            final String string = (String) smpc.type.getRawType().newInstance();
            System.out.format("string = \"%s\"",string);
        }
    
        static abstract class StrawManParameterizedClass
        {
            final TypeToken type = new TypeToken(getClass()) {};
        }
    }
    

    Of course if you need to call the constructor that will require some reflection, but that is very well documented, this trick isn't!

    Here is the JavaDoc for TypeToken.

提交回复
热议问题