尝试在客户端查看远程对象的属性时出现上述错误。在论坛(http://www.java-forums.org/networking/69581-rmi-classcastexception-proxy-cannot-cast.html)上阅读帖子之后,我认为这是因为远程对象在客户端和服务器中的不同包名中,所以我将客户端程序(甚至是远程接口)移到了与服务器和远程对象本身相同的包。但我仍然有同样的错误:
线程“main”中的异常java.lang.ClassCastException:com.sun.proxy。$ Proxy0无法强制转换为uk.ac.rm950.nonPublicDataSerializationServer.Employee at uk.ac.rm950.nonPublicDataSerializationServer.ClientSideProgram.main(ClientSideProgram.java:26)
这是我的远程界面:
package uk.ac.rm950.nonPublicDataSerializationServer;
public interface ObjectTransporter<T> extends java.rmi.Remote {
public T fetchObject() throws java.rmi.RemoteException;
}
远程对象类如下所示:
package uk.ac.rm950.nonPublicDataSerializationServer;
import java.rmi.RemoteException;
//import uk.ac.rm950.remoteInterface.ObjectTransporter;
public class Employee implements ObjectTransporter<Employee> {
public String name;
public Employee(String name) {
this.name = name;
}
@Override
public Employee fetchObject() throws RemoteException {
return this;
}
}
这是服务器程序:
package uk.ac.rm950.nonPublicDataSerializationServer;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
//import uk.ac.rm950.remoteInterface.ObjectTransporter;
public class ServerSideProgram {
public static void main(String[] args) {
System.setProperty("java.security.policy", "security/server.policy");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
Registry registry = LocateRegistry.createRegistry(1099);
ObjectTransporter<Employee> transportingObject = new Employee("Nemo");
ObjectTransporter<Employee> stub = (ObjectTransporter<Employee>) UnicastRemoteObject.exportObject(transportingObject, 0);
registry.rebind("employee", stub);
System.out.println("Employee object bound.");
} catch (RemoteException e) {
System.out.println("Exception occurred on server side.");
e.printStackTrace();
}}}
这是客户端代码:
package uk.ac.rm950.nonPublicDataSerializationServer;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
//import uk.ac.rm950.remoteInterface.ObjectTransporter;
public class ClientSideProgram {
public static void main(String[] args) {
System.setProperty("java.security.policy", "security/server.policy");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
Registry registry = LocateRegistry.getRegistry();
ObjectTransporter<Employee> transportedObject = (ObjectTransporter<Employee>) registry.lookup("employee");
// Employee deserializedEmployee = (Employee) transportedObject.fetchObject();
System.out.println(transportedObject.fetchObject().name);
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}}}
当客户端程序执行时抛出错误,我无法弄清楚我做错了什么。
答案 0 :(得分:1)
您正在尝试将存根转换为远程对象本身。你不能。事实并非如此。你应该把它投射到远程接口:
ObjectTransporter<Employee>