I can't call method serve()
below.
public class GenericService {
public static class Service<T> {
public void serve(T t) {
System.out.println(t.toString());
}
}
public static Service<?> service = new Service<String>();
public static void main(String[] args) {
service.serve("Hello World!"); // 'serve(capture<?>)' cannot be applied to '(java.lang.String)'
}
}
How to call this method by force?
Why does Java dislike such calls?
UPDATE
The problem is not ClassCastException
as was proposed, because in that case I would be able to write
try {
service.serve("Hello World!"); // 'serve(capture<?>)' cannot be applied to '(java.lang.String)'
}
catch (ClassCastException e) {
System.err.println("You see!? This is why I was disliking your code!");
}
but I can't.
Why?
UPDATE 2
Now, when everybody said out, a new version:
public static Service<? extends String> service = new Service<String>();
public static void main(String[] args) {
service.serve("Hello World!"); // 'serve(capture<?>)' cannot be applied to '(java.lang.String)'
((Service<String>)service).serve("Hello World!"); // Unchecked cast: 'GenericService.Service<capture<? extends String>>' to 'GenericService.Service<String>'
}
what problem is here (don't regard that String
is final
)?