Reputation: 1270
The following throws a compile error because foo.getClass() isn't the same capture group as F extends Foo somehow:
public <F extends Foo> F create (final F foo){
return foo.getClass().cast(foo);
}
The following works fine.
return foo;
Thanks.
Upvotes: 0
Views: 59
Reputation: 360026
Object#getClass()
returns a Class<? extends Foo>
, not a Class<F extends Foo>
.
The actual result type is
Class<? extends |X|>
where|X|
is the erasure of the static type of the expression on which getClass is called.
The erasure of <F extends Foo>
is the upper bound, Foo
. Therefore the Class#cast()
call is roughly equivalent to
return (Foo) foo;
and not
return (F) foo;
As you've probably figured out by now, a Foo
is not an F extends Foo
(the declared method return type), so the compiler won't let you return a Foo
.
Upvotes: 3