Why does this use of Generics not throw a runtime or compile time exception?

后端 未结 3 654
一整个雨季
一整个雨季 2021-01-01 18:44

I\'ve got a method in a class that has a return type specified by use of a generic.

public class SomeMain {

  public static void main(String[] args) {

             


        
3条回答
  •  被撕碎了的回忆
    2021-01-01 19:17

    This is because overload resolution resolved your println call to println(Object), since there is no println(Integer).

    Keep in mind that Java's generics are erased at runtime. And casts like (E) "Foo" are removed, and are moved to call site. Sometimes this is not necessary, so things are casted to the right type only when needed.

    In other words, no casts are performed inside getFoo. The language spec supports this:

    Section 5.5.2 Checked Casts and Unchecked Casts

    • The cast is a completely unchecked cast.

      No run-time action is performed for such a cast.

    After erasure, getFoo returns Object. And that gets passed into println(Object), which is perfectly fine.

    If I call this method and pass foo.getFoo, I will get an error:

    static void f(Integer i) {
        System.out.println(i);
    }
    // ...
    f(foo.getFoo()); // ClassCastException
    

    because this time it needs to be casted.

提交回复
热议问题