views:

186

answers:

3

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 warning when "T extends Remote" and fix it (for a clean code)

Thnaks.

+1  A: 

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.

Carl Smotricz
+6  A: 

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.

Joachim Sauer
+1, well done on providing a solution that works. But I'm horrified at the crud Java makes you go through to do this! Maybe Scala's time has come.
Carl Smotricz
@Carl - off you go then ... and don't slam the door on the way out :-)
Stephen C
More on "Class Literals as Run-time Type Tokens": http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
trashgod
A: 

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.

miaubiz