Type safety: Unchecked cast from Object
Yes - this is a natural consequence of type erasure. If o
is actually an instance of Action<String>
that won't be caught by the cast - you'll only see the problem when you try to use it, passing in a ClientInterface
instead of a string.
You can get rid of the warning using:
@SuppressWarnings("unchecked")
as a function annotation, but you can't easily sort out the underlying problem :(
As usual, Jon Skeet is right.
To elaborate on the not-easily part of his answer:
Given
class ClientAction implements Action<ClientInterface> {}
You can write:
Class<? extends Action<ClientInterface>> c = ClientAction.class;
Action<ClientInterface> action = c.newInstance();
This eliminates both the cast and the warning, at the price of introducing a non-generic type so you can use .class
to get a sufficiently accurately typed Class
object.
The warning means that the compiler can't guarantee type safety even if the casting works fine at runtime. Due to erasure, at runtime the casting is simply a casting to Action. It is possible that the underlying generic class is not of type ClientInterface as expected. In this case, the problem will appear later (maybe even much later), as a ClassCastException.
In this specific case I recommend suppressing this specific warning by the following compiler directive:
@SuppressWarnings("unchecked")