【问题标题】:Java RMI proxy-casting issueJava RMI 代理转换问题
【发布时间】:2014-05-22 10:45:18
【问题描述】:

我正在尝试让 RMI 程序运行。到目前为止,服务器正常启动,但客户端无法将远程对象投射到接口。

线程“AWT-EventQueue-0”java.lang.ClassCastException 中的异常: com.sun.proxy.$Proxy0 无法转换为 MonitorClient.InterfaceMonitor

我找到的所有其他答案都是针对最终用户使用 InterfaceMonitorImpl 等效项(客户端未知)而不是 Interface 的情况。这不是我的情况,我真的很茫然——RMI 简直是噩梦。

服务器端

主要:

    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;
    }

}

客户端

    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);
    }

InterfaceMonitor.java 也在客户端。

感谢您的宝贵时间!

【问题讨论】:

  • 它必须是相同的接口,而不仅仅是具有相同名称和方法的接口。这也是使用的代码吗?接口有一个checkAge 方法,而实现有一个counter 方法。

标签: java rmi


【解决方案1】:

显然,您必须有两份InterfaceMonitor: 的副本,一份在MonitorClient 中,一份在可能类似于MonitorServer. 的地方,这构成了两个不同的类。不是同一类的两个副本。类名、包、方法声明、继承……都必须相同。

【讨论】:

  • 谢谢!现在我收到“java.rmi.NoSuchObjectException: no such object in table”错误,在从服务器包交叉导入 InterfaceMonitor 之后(不满意,但它可以作为演示在本地运行)
  • 表示远程对象已被取消导出。解决方法是将LocateRegistry.createRegistry(1099)的结果存入静态变量中。