Create instance of generic type in Java?

后端 未结 27 3094
佛祖请我去吃肉
佛祖请我去吃肉 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<E> entity;

    2

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

    3.

    E e = getEntity(entity);

    0 讨论(0)
  • 2020-11-21 06:51

    Here is an option I came up with, it may help:

    public static class Container<E> {
        private Class<E> clazz;
    
        public Container(Class<E> clazz) {
            this.clazz = clazz;
        }
    
        public E createContents() throws Exception {
            return clazz.newInstance();
        }
    }
    

    EDIT: Alternatively you can use this constructor (but it requires an instance of E):

    @SuppressWarnings("unchecked")
    public Container(E instance) {
        this.clazz = (Class<E>) instance.getClass();
    }
    
    0 讨论(0)
  • 2020-11-21 06:53

    You'll need some kind of abstract factory of one sort or another to pass the buck to:

    interface Factory<E> {
        E create();
    }
    
    class SomeContainer<E> {
        private final Factory<E> factory;
        SomeContainer(Factory<E> factory) {
            this.factory = factory;
        }
        E createContents() {
            return factory.create();
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:53

    When you are working with E at compile time you don't really care the actual generic type "E" (either you use reflection or work with base class of generic type) so let the subclass provide instance of E.

    Abstract class SomeContainer<E>
    {
    
        abstract protected  E createContents();
        public doWork(){
            E obj = createContents();
            // Do the work with E 
    
         }
    }
    
    
    BlackContainer extends SomeContainer<Black>{
        Black createContents() {
            return new  Black();
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:53

    You can achieve this with the following snippet:

    import java.lang.reflect.ParameterizedType;
    
    public class SomeContainer<E> {
       E createContents() throws InstantiationException, IllegalAccessException {
          ParameterizedType genericSuperclass = (ParameterizedType)
             getClass().getGenericSuperclass();
          @SuppressWarnings("unchecked")
          Class<E> clazz = (Class<E>)
             genericSuperclass.getActualTypeArguments()[0];
          return clazz.newInstance();
       }
       public static void main( String[] args ) throws Throwable {
          SomeContainer< Long > scl = new SomeContainer<>();
          Long l = scl.createContents();
          System.out.println( l );
       }
    }
    
    0 讨论(0)
  • 2020-11-21 06:55

    Java unfortunatly does not allow what you want to do. See the official workaround :

    You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:

    public static <E> void append(List<E> list) {
        E elem = new E();  // compile-time error
        list.add(elem);
    }
    

    As a workaround, you can create an object of a type parameter through reflection:

    public static <E> void append(List<E> list, Class<E> cls) throws Exception {
        E elem = cls.newInstance();   // OK
        list.add(elem);
    }
    

    You can invoke the append method as follows:

    List<String> ls = new ArrayList<>();
    append(ls, String.class);
    
    0 讨论(0)
提交回复
热议问题