ICE - 如何将实现转换为代理?

ICE - How to cast implementation to proxy?

我在我的代码中使用了 ICE。我想要 运行 需要 GameObserverPrx 作为参数的函数。我不想按值传递 GameObserver,我在切片接口中使用 GameObserver* 来传递代理。

我应该使用什么函数将 GameObserver 转换为 GameObserverPrx? 第二个问题——为什么 ICE 不能代替我来做? 我正在互联网上寻找答案。我只找到了 ObjectAdapter.checkedCast 但它还有另一个用途。

这是错误:

The method addObserver(String, GameObserverPrx, Current) in the type GameProxyImpl is not applicable for the arguments (String, GameObserverImpl, null) PrzeciwnikKomputerowy.java /warcaby-serwer/src/main/java/sr/warcaby/serwer line 74 Java Problem

以下是我的代码片段: 在这一行中,我看到了一个错误。

partia.addObserver(token, new GameObserverImpl(this)), null);

GameObserver 实现片段:

class GameObserverImpl extends _GameObserverDisp { //extends IGameObserverPOA{

    private static final long serialVersionUID = 1L;
    PrzeciwnikKomputerowy p;
    public GameObserverImpl(PrzeciwnikKomputerowy p) {
        this.p = p;
    }

api.ice 的片段:

interface GameObserver {
    void notifyObserver(  CORBAMove lastMove);
};



interface GameProxy {
    void addObserver(  string token,   GameObserver* o) throws MyException;
    bool isMyTurn(  string token) throws MyException;
    void doMove(  string token,   CORBAMove move) throws MyException;
    Position getPosition(  string token) throws MyException;
    string showPosition(  string token) throws MyException;
};

不要对 CORBAMove 这个名字感到困惑。我使用的是 CORBA,但我将代码更改为 ICE。

我找到了问题的答案。 现在我的应用程序按预期运行。

我编写了从 Ice.Object 创建 ObjectPrx 的方法。 此方法使用反射来查找指定 class.

的转换方法

在这个网站上我找到了我需要的功能:https://doc.zeroc.com/display/Ice/Object+Incarnation+in+Java#ObjectIncarnationinJava-proxies

最重要的一行是:ObjectPrx objectPrx = adapter.addWithUUID(iceObject).

然后我使用从反射中获得的方法 xxxPrxHelper.checkedCast(objectPrx) 进行投射。 这是更改后的代码:

partia.addObserver(token, (GameObserverPrx)
    serwer.createProxyForObject(observer, GameObserverPrxHelper.class), null)

classServerImpl 中的方法:

public ObjectPrx createProxyForObject(Ice.Object iceObject, Class<?> clazz) {
    ObjectPrx objectPrx = adapter.addWithUUID(iceObject);
    try {
        Method method = clazz.getMethod("checkedCast", ObjectPrx.class);
        objectPrx =  (ObjectPrx) method.invoke(null, objectPrx);//adapter.createIndirectProxy(id));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return objectPrx;

方法 createProxyForObject 使用在服务器构造函数中初始化的普通适配器(因为 PrzeciwnikKomputerowy class 仍然是服务器程序的一部分)。

    Ice.Communicator communicator = Ice.Util.initialize(args); 

    ObjectAdapter adapter = communicator.createObjectAdapter("ChessServer");