Java RMI代理问题

我收到此错误:

java.lang.ClassCastException: $Proxy0 cannot be cast to rmi.engine.Call at Main.main(Main.java:39) 

我的AbstractCall类都扩展了Remote

呼叫:

 public class Call extends UnicastRemoteObject implements rmi.engine.Abstract { public Call() throws Exception { super(Store.PORT, new RClient(), new RServer()); } public String getHello() { System.out.println("CONN"); return "HEY"; } } 

抽象:

 public interface Abstract extends Remote { String getHello() throws RemoteException; } 

这是我的主要内容:

 public static void main(String[] args) { if (args.length == 0) { try { System.out.println("We are slave "); InetAddress ip = InetAddress.getLocalHost(); Registry rr = LocateRegistry. getRegistry(ip.getHostAddress(), Store.PORT, new RClient()); Object ss = rr.lookup("FILLER"); System.out.println(ss.getClass().getCanonicalName()); System.out.println(((Call)ss).getHello()); } catch (Exception e) { e.printStackTrace(); } } else { if (args[0].equals("master")) { // Start Master try { RMIServer.start(); } catch (Exception e) { e.printStackTrace(); } } 

Netbeans说问题出在第39行

  System.out.println(((Call)ss).getHello()); 

输出如下:

跑:

 We are slave Connecting 10.0.0.212:5225 $Proxy0 java.lang.ClassCastException: $Proxy0 cannot be cast to rmi.engine.Call at Main.main(Main.java:39) BUILD SUCCESSFUL (total time: 1 second) 

我在cmd上运行一个主机,在端口5225上监听。

$Proxy0类是一个动态代理 ,也就是说,一个类是在运行时由java生成的。

此类应实现Abstract接口,但不扩展Call 。 所以你不能将它转发给Call (这给了一个类强制转换),但是将它向下转换为Abstract应该没问题。

如果使用RMI,则只应通过接口与远程对象通信。

PS: Abstract是一种令人困惑的名字。 我真的以为你先说的是抽象课 。 如果可能的话我会重命名。 对于rmi.engine ,更喜欢类似org.myproject东西,以避免与JDK的内部类混淆。