开发者

How can i remove an unckecked cast warning in java?

开发者 https://www.devze.com 2022-12-17 17:07 出处:网络
i have this piece of code: import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException;

i have this piece of code:

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;

public class ClientLookup<T extends Remote> {
 private T sharedObject;

 public void lookup(String adress) throws MalformedURLException, RemoteException, NotBoundException {
   sharedObject = (T) Naming.lookup(adress);
 }

 public T getSharedObject() {
   return sharedObject;
 }
}

The part with "(T) Naming.lookup(adress)" is giving me a warning: "Type safety: Unchecked cast from Remote to T"

I don't wanto to use "@SuppressWarnings("unchecked")", i just want to know why is it showing a wa开发者_StackOverflow社区rning when "T extends Remote" and fix it (for a clean code)

Thnaks.


The "unechecked cast" here means that Java can't verify if the object to be cast is actually of type T at runtime, since the type T is not known at runtime. At most it can verify that it is actually of type Remote.

A common workaround to this problem is to provide a Class<T> object to define the type:

public class ClientLookup<T extends Remote> {
  private T sharedObject;
  private Class<T> clazz;

  public ClientLookup(Class<T> clazz) {
    this.clazz = clazz;
  }

  public void lookup(String adress) throws MalformedURLException, RemoteException, NotBoundException {
    sharedObject = clazz.cast(Naming.lookup(adress));
  }

  public T getSharedObject() {
    return sharedObject;
  }
}

This way you make the type T explicit and known at runtime.


Since Naming.lookup() returns a Remote so your cast is in fact unchecked.

If you had a handle to the class of T you could use:

private Class<T> clazz;
clazz.cast(Naming.lookup(address)); 

which would return a T. Because of erasure you would need to give the class in the constructor, or use some other hackery such as in: MoreTypes.java.


There are a few warnings connected with typecasting generics that I've never been able to eliminate. I just gave up and used @SuppressWarnings.

Another alternative, depending on IDE, is to make the compiler less sensitive to problems. Eclipse lets me selectively turn off specific warnings. I find the "missing serial UID" warning on Swing GUI classes (among others) quite annoyingly superfluous, and deactivated them. If I get too annoyed by these type cast warnings, they'll suffer the same fate.

0

精彩评论

暂无评论...
验证码 换一张
取 消