Search code examples
javarmi

Java RMI proxy-casting issue


I'm trying to get a RMI program to work. So far, the server starts up correctly but the client fails casting the remote object to the interface.

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to MonitorClient.InterfaceMonitor

All other answers I've found are for cases where the end user has cast the equivalent of InterfaceMonitorImpl (unknown to the client) instead of the Interface instead. This is not my case and I'm really at a loss here — RMI is nightmare-ish.

Server side

Main:

    InterfaceMonitor obj;
    try {
        LocateRegistry.createRegistry(1099);

        InterfaceMonitor stub = (InterfaceMonitor) UnicastRemoteObject.exportObject(new InterfaceMonitorImpl(), 0);

        Registry registry = LocateRegistry.getRegistry();
        registry.bind("imon", stub);

        System.out.println("Server ready");
    } catch (RemoteException | AlreadyBoundException ex) {
        System.out.println("Server error: " + ex.toString());
    }

InterfaceMonitor.java:

public interface InterfaceMonitor extends Remote {
    int checkAge() throws RemoteException; 
}

InterfaceMonitorImpl.java:

public class InterfaceMonitorImpl implements InterfaceMonitor {

    public InterfaceMonitorImpl() throws RemoteException {

    }

    @Override
    public int counter() throws RemoteException {
        return 10;
    }

}

Client side

    try {
        Registry reg = LocateRegistry.getRegistry(null);
        InterfaceMonitor im = (InterfaceMonitor) reg.lookup("imon");

        int counter = im.counter();
        System.out.println("Counter: " + counter);
    } catch (NotBoundException | RemoteException ex) {
        Logger.getLogger(MonitorGUI.class.getName()).log(Level.SEVERE, null, ex);
    }

The InterfaceMonitor.java is also on the client side.

Thanks for your time!


Solution

  • Obviously you must have two copies of InterfaceMonitor: one in MonitorClient and one in what may be something like MonitorServer. That makes two different classes. Not two copies of the same class. The class name, package, method declarations, inheritance, ... all have to be the same.