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

后端 未结 3 675
一整个雨季
一整个雨季 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:05

    I'd like to add that during the type erasure process, the Java compiler replaces the unbounded type parameter E with Object, therefore the Foo class is actually compiled into:

    public static class Foo {
        public Object getFoo() {
            return "Foo";
        }
    }
    

    That's why the following code is valid (cast is not needed):

    Object obj = foo.getFoo();
    System.out.println(obj);
    

    At the same time, the next code snippet produces a compile-time error, as expected:

    Foo foo = new Foo();
    String fooString = foo.getFoo(); // you're trying to trick the compiler (unsuccessfully)
               ^
    incompatible types: Integer can not be converted to String
    

    And that's the main responsibility of generics - compile-time checks.

    Yet there is another side of the story - execution-time casts. For example, if you write:

    Integer value = foo.getFoo();
    

    you get a ClassCastException thrown at runtime (the Java compiler inserts a checkcast instruction that examines whether the result of the foo.getFoo() can be cast to Integer).

提交回复
热议问题