Java RMI 代理问题 [英] Java RMI Proxy issue
问题描述
我收到此错误:
java.lang.ClassCastException: $Proxy0 cannot be cast to rmi.engine.Call
at Main.main(Main.java:39)
我的Abstract
和Call
类都扩展了Remote
.
My Abstract
and Call
class both extend 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 行,即
Netbeans says the problem is on line 39 which is
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 中运行一个 master 监听端口 5225.
I am running a master in cmd listening on port 5225.
推荐答案
$Proxy0
类是一个 动态代理,即java在运行时生成一个类.
The class $Proxy0
is a dynamic proxy, that is, a class is generate by java at run-time.
这个类应该实现接口Abstract
,但不扩展Call
.所以你不能将它向下转换为 Call
(这给出了一个类转换),但是将它向下转换为 Abstract
应该没问题.
This class should implement the interface Abstract
, but does not extend Call
. So you can't downcast it to Call
(this gives a class cast), but downcasting it to Abstract
should be ok.
如果你使用 RMI,你应该只通过接口与远程对象通信.
If you use RMI, you should only communicate with remote object through interfaces.
PS:Abstract
是一个令人困惑的名字.我真的以为你在说抽象类第一的.如果可能,我会重命名它.rmi.engine
也一样,更喜欢 org.myproject
之类的东西,以免与 JDK 的内部类混淆.
PS: Abstract
is kind of a confusing name. I really thought that you were speaking of abstract class first. I would rename that if possible. Same for rmi.engine
, prefer something like org.myproject
, to avoid confusion with internal class of the JDK.
这篇关于Java RMI 代理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!