I try to cast an object to my Action class, but it results in a warning:
Type safety: Unchecked cast from Object to Action<ClientInterface> Action<ClientInterface> action = null; try { Object o = c.newInstance(); if (o instanceof Action<?>) { action = (Action<ClientInterface>) o; } else { // TODO 2 Auto-generated catch block throw new InstantiationException(); } [...]
Thank you for any help
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around.
1 Answer. Show activity on this post. Adding @Suppress("UNCHECKED_CAST") (also possible through IDEA's Alt + Enter menu) to any of statement, function, class and file should help.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With