目录

Java Generics - 无静态字段( No Static field)

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

例子 (Example)

package com.iowiki;
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都有一个静态类型变量,因此无法确定其类型。 因此不允许使用静态类型参数。

↑回到顶部↑
WIKI教程 @2018