Create instance of generic type in Java?

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

    what you can do is -

    1. First declare the variable of that generic class

      2.Then make a constructor of it and instantiate that object

    2. Then use it wherever you want to use it

    example-

    1

    private Class entity;

    2

    public xyzservice(Class entity) {
            this.entity = entity;
        }
    
    
    
    public E getEntity(Class entity) throws InstantiationException, IllegalAccessException {
            return entity.newInstance();
        }
    

    3.

    E e = getEntity(entity);

提交回复
热议问题