简体   繁体   English

泛型-类型推断和类型擦除

[英]Generics - type inference and type erasure

This code compiled with Java SE-1.7 gives following output (below). 用Java SE-1.7编译的此代码提供以下输出(如下)。 I understand, the inferred type of value should be Object, how does it come that there are String and Integer Types recognized? 我知道,值的推断类型应该是Object,为什么会识别出String和Integer Types?

public class Generics1 {

    public class Pocket<T>{
      public T value;
      public void set( T value ) { this.value = value; }
      public void set( String value ) { this.value = (T)value; } //warning
    }

    public static void main(String[] args) {

        Pocket<Object> intPocket =  new Generics1().new Pocket<>();

        intPocket.set("foo");
        System.out.println(intPocket.value);
        System.out.println(intPocket.value.getClass().getName());

        intPocket.set(12);
        System.out.println(intPocket.value);
        System.out.println(intPocket.value.getClass().getName());
    }
}

Output: 输出:

foo
java.lang.String
12
java.lang.Integer

value.getClass() returns the runtime type of the object that value refers to. value.getClass()返回value引用的对象的运行时类型。

An Integer stored in a field of type Object is still an Integer . 一个Integer存储在类型的字段Object仍然是一个Integer

The variable public T value has its type erased, so it is essentially public Object value . 变量public T value的类型已删除,因此本质上是public Object value But even if your variable doesn't specify the exact type, the instance itself still knows what class it is. 但是,即使您的变量没有指定确切的类型, 实例本身仍然知道它是什么类。

Eg 例如

Object value = "bananas";
System.out.println(value.getClass().getName());

Output: 输出:

java.lang.String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM