Why can't you create an instance of a generic type using “new” operator?

后端 未结 4 1782
萌比男神i
萌比男神i 2021-02-03 11:35

I found a lot of posts about how to overcome this limitation, but none about why this limitation exists (except this one, which just mentions it has to do with type era

4条回答
  •  孤街浪徒
    2021-02-03 12:16

    Creating a class from a generic. Do note that this relies on the class being parametrized. This returns the class object of the generic, through which you can perform further reflection on to create an object.

     public static  Class getClassFromGeneric(
                Object parentObj,
                int oridnalParamterizedTypeIndex) throws Exception{
              Type[] typeArray = getParameterizedTypeListAsArray(parentObj);
              return (Class)typeArray[oridnalParamterizedTypeIndex];
        }
    
        public static  Type[] getParameterizedTypeListAsArray(Object parentObj){
            try{
                return  ((ParameterizedType) parentObj.getClass()
                        .getGenericSuperclass())
                        .getActualTypeArguments();
            }
            catch(ClassCastException e){
                logger.log(Level.SEVERE, "Most likely, somewhere in your inhetirance chain,"
                        + "there is a class that uses a raw type and not the generic param."
                        + "See: http://stackoverflow.com/questions/23074446/java-lang-classcastexception-java-lang-class-cannot-be-cast-to-java-lang-reflec"
                        + " for more info",e);
                throw e;
            }
        }
    

    Usage:

    public class GenericBaseClass{}
    public class GenericImpl extends GenericBaseClass{
        public static void main(String[] args){
            new GenericImpl();
        }
    
        public GenericImpl(){
            Class tClazz = getClassFromGeneric(this,0);
            Constructor constructor = tClazz.getConstructor();
            T newT = constructor.newInstance();
        }
    }
    

    Contrary to popular belief, generic information at the class level is not "erased".

提交回复
热议问题