Java RMI proxy-casting issue

孤者浪人 提交于 2019-11-26 23:48:32

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/23804625/java-rmi-proxy-casting-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!