Java Generics 简明教程

Java Generics - No Instance

不能在方法内部使用类型参数实例化其对象。

public static <T> void add(Box<T> box) {
   //compiler error
   //Cannot instantiate the type T
   //T item = new T();
   //box.add(item);
}

如需实现这种功能,请使用反射。

public static <T> void add(Box<T> box, Class<T> clazz)
   throws InstantiationException, IllegalAccessException{
   T item = clazz.newInstance();   // OK
   box.add(item);
   System.out.println("Item added.");
}

Example

package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args)
      throws InstantiationException, IllegalAccessException {
      Box<String> stringBox = new Box<String>();
      add(stringBox, String.class);
   }

   public static <T> void add(Box<T> box) {
      //compiler error
      //Cannot instantiate the type T
      //T item = new T();
      //box.add(item);
   }

   public static <T> void add(Box<T> box, Class<T> clazz)
      throws InstantiationException, IllegalAccessException{
      T item = clazz.newInstance();   // OK
      box.add(item);
      System.out.println("Item added.");
   }
}

class Box<T> {
   private T t;

   public void add(T t) {
      this.t = t;
   }

   public T get() {
      return t;
   }
}

这会产生以下结果 −

Item added.