Domanda

I am using Future objects

Future<String> res = (Future<String>) result;

Where result is of type Object. However I get this warning

Type safety: Unchecked cast from Object to Future<String>

How do I check this casting

Thanks

È stato utile?

Soluzione

Look on interface

public interface Future<V> {//...}

So when you use method that returns you future you can simply put there parameter to be sure what it is returning(it might be also some kind of abstraction). Try to think about how to improve your code that make you to check the instance of returning object or create some interface that can be applyied to your future to be more safe.

public interface SomeInterface{//...}
public Future<SomeInterface> yourMethod(){};

Try to look deeper into architecture of your solution to avoid unchecked sitution and reconsider it, there is always some solution that can by applied to create more safe code.

Altri suggerimenti

You can't - except, if you can change the origin of result to the appropriate type. But otherwise, your compiler can't be sure which type result has and therefore a cast must be unsafe. You can disable the compiler warning through @SuppressWarnings("unchecked") although, indicating that you are aware of an unsafe cast.

You can remove it by using @SuppressWarnings("unchecked"), which doesn't shows warning but It is not good practice because you will get a ClassCastException at runtime, because the generics cannot block this from happening in this case. You have to sure before adding @SuppressWarnings that you are casting same object.

Go through this link: How do I address unchecked cast warnings?

Thanks.

I realize this is an old thread, but I can across it searching for the solution to the same problem. My solution was to specify the object type I was returning in the class declaration.

public class MyClass implements Callable<object type returned>{

Hope this helps someone in the future.

If you happen to be using a Callable instantiated via an anonymous inner class another reason for this warning could be if the declaration of the Callable is generic. I had to refer to <T> on both sides of the declaration:

Callable<Boolean> callable = new Callable<Boolean>() {
        ^^^^^^^^^
    @Override
    public Boolean call() throws Exception {
       ...
   }

};

Probably completely obvious, but it took me a bit to figure this out.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top