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) {
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
).