Create instance of generic type in Java?

后端 未结 27 3143
佛祖请我去吃肉
佛祖请我去吃肉 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:03

    package org.foo.com;
    
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    
    /**
     * Basically the same answer as noah's.
     */
    public class Home
    {
    
        @SuppressWarnings ("unchecked")
        public Class getTypeParameterClass()
        {
            Type type = getClass().getGenericSuperclass();
            ParameterizedType paramType = (ParameterizedType) type;
            return (Class) paramType.getActualTypeArguments()[0];
        }
    
        private static class StringHome extends Home
        {
        }
    
        private static class StringBuilderHome extends Home
        {
        }
    
        private static class StringBufferHome extends Home
        {
        }   
    
        /**
         * This prints "String", "StringBuilder" and "StringBuffer"
         */
        public static void main(String[] args) throws InstantiationException, IllegalAccessException
        {
            Object object0 = new StringHome().getTypeParameterClass().newInstance();
            Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();
            Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();
            System.out.println(object0.getClass().getSimpleName());
            System.out.println(object1.getClass().getSimpleName());
            System.out.println(object2.getClass().getSimpleName());
        }
    
    }
    

提交回复
热议问题