分类: Java
2010-07-09 12:03:45
Hist:
100709, draft
JLS 4.8中是这样定义Raw Type的:
To facilitate interfacing with non-generic legacy code, it is also
possible to use as
a type the erasure of a parameterized type. Such a type is called a raw
type.
More precisely, a raw type is define to be either:
• The name of a generic type declaration used without any
accompanying
actual type parameters.
• Any non-static type member of a raw type R that is not inherited
from a superclass
or superinterface of R.
意译如下:
为了方便兼容以前代码, 参数化的类型可以不指定参数而使用. 这种不指定参数的参数化类型,就称为raw type. 具体的就是下面两种情况之一:
1) 泛型类型不指定参数, 直接使用的, 是raw type.
2) raw type的类型R, 它的非static成员(包括成员变量和方法),如果不是继承自R的父类或父接口的化, 也是raw type.
具体的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class CarColor { public final static int RED = 1; public final static int BLUE = 2; public final static int YELLOW = 3; public int color; public String toString(){ switch (color){ case RED: return "red"; case BLUE: return "blue"; case YELLOW: return "yellow"; default: return "n/a"; } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
public class Car public static void main(String[] args) { CarColor color = new CarColor(); color.color = CarColor.RED; // ok case Car System.out.println("okCase: "+okCase); // raw type 1 case, //没有指定类型参数 Car rawTypeCase = new Car(color); // raw type 2 case, // Car是raw type, 所以它的成员setColor()也是raw type. // 入口参数color不能被编译器检查是否符合类型参数, // 因为raw type是没有类型参数信息. rawTypeCase.setColor(color); System.out.println("rawType1Case: "+rawTypeCase); } private T color; public Car(T color){ this.color = color; } public void setColor(T color){ this.color = color; } public T getColor(){ return color; } public String toString(){ return "The car color is "+color+"."; } } |
Raw Type的翻译,网络上见到有翻作”未经处理类型”, 比较莫名, 感觉还是”原生类型”更妥帖些, raw type其实就是没有指定类型参数的泛型而已, 原本就是先前泛型没有出现在java时的使用情况。
1. JLS 3nd