Chinaunix首页 | 论坛 | 博客
  • 博客访问: 197223
  • 博文数量: 69
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 720
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-03 11:35
文章分类

全部博文(69)

文章存档

2011年(13)

2010年(46)

2009年(10)

我的朋友

分类: Java

2010-07-09 12:03:45

JLS100709Raw Type(原生类型)

 

@ http://zcatt.cublog.cn

 

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 okCase = new Car(color);

       System.out.println("okCase: "+okCase);

 

       // raw type 1 case,

       //没有指定类型参数, Carraw type

       Car rawTypeCase = new Car(color);

 

       // raw type 2 case,

       // Carraw 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时的使用情况。

 

 

REF

1.       JLS 3nd

2.       JVM 2nd
Locations of visitors to this page

阅读(2276) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~