开发手册 欢迎您!
软件开发者资料库

Java泛型 - 没有实例

Java Generics No Instance - 从基本到高级概念的简单简单步骤学习Java泛型,其中包括概述,环境设置,通用类,类型参数命名约定,类型推断,多类型参数,参数化类型,原始类型,通用方法,有界类型参数,多个边界,内建类,通用列表,通用集,通用映射,通配符,上限有界通配符,无界通配符,下限有界通配符,通配​​符使用指南,类型擦除,通用类型擦除,通用方法擦除,泛型限制,无原始类型,无实例,无静态字段,无转换,无instanceOf,无数组,无例外,无过载。

类型参数不能用于在方法中实例化其对象.

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.it1352; 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.