我正在尝试让 RMI 程序运行。到目前为止,服务器启动正确,但客户端无法将远程对象转换到接口(interface)。
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to 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 也在客户端。
感谢您的宝贵时间!
最佳答案
显然,您必须拥有两份 InterfaceMonitor 副本:
一份位于 MonitorClient
中,另一份可能位于 MonitorServer 之类的位置。
这使得两个不同的副本类。不是同一类的两个副本。类名、包、方法声明、继承……都必须相同。
关于Java RMI 代理转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23804625/