📜  Java泛型-无实例

📅  最后修改于: 2020-11-15 04:08:35             🧑  作者: Mango


类型参数不能用于实例化方法内部的对象。

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

要实现此类功能,请使用反射。

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

package com.tutorialspoint;

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

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

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

class Box {
   private T t;

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

   public T get() {
      return t;
   }   
}

这将产生以下结果-

Item added.