Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type safety: Unchecked cast from Object

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

like image 932
Matthew Avatar asked Apr 07 '10 13:04

Matthew


People also ask

How can I avoid unchecked cast warnings?

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.

What is a unchecked cast?

Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around.

How do you stop unchecked cast Kotlin?

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.


2 Answers

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 :(

like image 180
Jon Skeet Avatar answered Sep 27 '22 00:09

Jon Skeet


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.

like image 37
meriton Avatar answered Sep 24 '22 00:09

meriton