Java 泛型 - 无实例
类型参数不能用于在方法内实例化其对象。
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."); }
示例
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.