Consider the following code:
class ExtType extends MyType{};
class MyClass {
MyType myField;
public <T extends MyType> T foo(Class<T> clazz) {
return (T)myField;
}
}
Now I want to call foo method, I can do this two ways:
1 way:
(new MyClass()).foo(ExtType.class);
2 way:
(new MyClass()).<ExtType>foo(ExtType.class);
Interesting, that even the method is declared as parametrized, Eclipse doesn’t issue
any warning on 1 call.
Here is my question, in first code snippet, which of Ts is used in casting return value.
Is it a T from parameter or T from return value? Why if I don’t explicitly specify return type (as in “1 way”) no warning is issued?
Normally the parameter type is used but if there is a return type defined (like in way 2) the compiler would check that as well.
The return type declaration would be necessary if there’s no parameter to get the type of
Tfrom, which then is called type inference. Thus you could even write:In some cases you need to help the compiler and specify the type to be used thus getting code like
(new MyClass()).<ExtType>foo(ExtType.class);. Note, however, that if you’d define different types, e.g.(new MyClass()).<MyType>foo(ExtType.class);, you’d get a compile time error, since the compiler now doesn’t know which one is used.