简体   繁体   中英

Generics - type inference and type erasure

This code compiled with Java SE-1.7 gives following output (below). I understand, the inferred type of value should be Object, how does it come that there are String and Integer Types recognized?

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.

An Integer stored in a field of type Object is still an Integer .

The variable public T value has its type erased, so it is essentially 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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