导出内部对象

可以说我有一台服务器和一台客户端。 客户端从服务器请求服务对象。 该对象通过复制传输,但也提供回调方法(bar)。 如果客户端然后要求服务器更新该对象(updateValue),则服务器将使用RMI调用bar()。 我试过这样的东西,但是当从服务器请求对象时我得到一个错误:“无法将com.sun.proxy。$ Proxy1的实例分配给ServiceObjImpl类型的ServiceObjImpl.barWrapper $ ServiceWbImpl实例中的BarWrapper”

服务对象接口:

public interface ServiceObject{ public int foo(); public void bar(int var) throws RemoteException; } 

服务器接口

 public interface Service extends Remote { public ServiceObject get() throws RemoteException; public void updateValue(int var) throws RemoteException; } 

服务器实现

 public class Server extends UnicastRemoteObject implements Service { private static final long serialVersionUID = 247610230875286173L; private ServiceObject serviceObj = null; public Server() throws RemoteException { super(); serviceObj = new ServiceObjImpl(); } public void updateValue(int var){ try { serviceObj.bar(var); } catch (RemoteException e) { e.printStackTrace(); } } public ServiceObject get() throws RemoteException { return serviceObj; } } 

服务对象实现

 class ServiceObjImpl implements ServiceObject, Serializable{ private static final long serialVersionUID = 1576043218876737380L; private int data = 0; private BarWrapper barWrapper = new BarWrapper(); private class BarWrapper extends UnicastRemoteObject implements Remote{ private static final long serialVersionUID = -5451253032897838145L; public BarWrapper() throws RemoteException { super(); } public void bar(int value){ data = value; } } public ServiceObjImpl() throws RemoteException { super(); } public int foo() { return data; } public void bar(int value) throws RemoteException { barWrapper.bar(value); } } 

客户实施

 public class Client{ private Service server = null; private ServiceObject obj = null; public void get(){ try { obj = server.get(); } catch (RemoteException e) { } } public void updateValue(int value){ try { server.updateValue(value); } catch (RemoteException e) { } } public void foo(){ System.out.println(obj.foo()); } } 

BarWrapper不实现远程以外的任何远程接口。 但它是一个导出的远程对象,因此它作为存根传递,而不是作为自己的类型传递。 所以客户端的类型必须是存根实现的类型,而不是具体的类型BarWrapper这就是你获得exception的原因

解:

  • 为它定义一个新的远程接口
  • 让它实现,和
  • 将字段barWrapper的声明从BarWrapper类型BarWrapper为新的远程接口类型。