【发布时间】: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方法。