Java Generics - 无静态字段

使用泛型,不允许输入类型参数是静态的.由于静态变量在对象之间共享,因此编译器无法确定要使用的类型.如果允许静态类型参数,请考虑以下示例.

示例

package com.it1352; 
public class GenericsTester {
   public static void main(String[] args) {
      Box<Integer> integerBox = new Box<Integer>();
	  Box<String> stringBox = new Box<String>();
	  
      integerBox.add(new Integer(10));
      printBox(integerBox);
   }

   private static void printBox(Box box) {
      System.out.println("Value: " + box.get());
   }  
}

class Box<T> {
   //compiler error
   private static T t;

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

   public T get() {
      return t;
   }   
}

由于stringBox和integerBox都有一个静态类型变量,因此无法确定其类型.因此不允许使用静态类型参数.