RMI + Java 反射

Jas*_*n S 5 java reflection rmi

我正在使用 RMI 允许通过 MATLAB 访问我的 Java 应用程序,该应用程序在另一个 JVM 中运行。MATLAB 有一个很好的接口来打印 Java 对象的方法。但是它在 RMI 中失败了,因为它获得的对象是一个代理。

所以我想添加我自己的方法来提取/打印远程接口的功能(RMI 显然不能直接访问导出的远程接口中不可用的方法)。

我怎么能用反射来做到这一点,无论是在 RMI 连接的客户端还是在服务器端?我没有太多使用反射的经验。下面的用例。

编辑:我最困惑的是给定一个任意对象 X(包括 X 是 RMI 代理的地方),我如何使用反射来获取该对象实现的接口?

java类:

/** client-side remote describer */
class RemoteDescriber
{
    RemoteDescription describe(Remote remote) { ... }
}

/* representation of remote interfaces implemented by an object */
class RemoteDescription implements Serializable
{
    /* string representation of remote interfaces implemented by an object */
    @Override public String toString() { ... }

    /* maybe there are other methods permitting object-model-style navigation
     * of a remote interface
     */
}

interface FooRemote extends Remote
{
    /* some sample methods */
    public int getValue() throws RemoteException;
    public void setValue(int x) throws RemoteException;
    public void doSomethingSpecial() throws RemoteException;
    /* other methods omitted */        

    /** server-side */
    public RemoteDescription describe() throws RemoteException;        
}
Run Code Online (Sandbox Code Playgroud)

和 MATLAB 中的示例客户端会话

x = ...;     % get something that implements FooRemote
describer = com.example.RemoteDescriber;
% describer is a client-side Java object

description1 = describer.describe(x)

%%% prints a description of the FooRemote interface 
%%% obtained by the client-side RemoteDescriber

description2 = x.describe()

%%% prints a description of the FooRemote interface 
%%% obtained on the server-side by x itself, and marshalled
%%% to the client
Run Code Online (Sandbox Code Playgroud)

Erh*_*obl 1

客户端上的对象是代理:它们称为存根。要从中获取接口,您应该编写如下代码,o您的对象在哪里:

Class c = o.getClass();
Class[] theInterfaces = c.getInterfaces();
for (int i = 0; i < theInterfaces.length; i++) {
   String interfaceName = theInterfaces[i].getName();
   System.out.println(interfaceName);
}
Run Code Online (Sandbox Code Playgroud)

存根是自动生成的:因此您不应该在其中实现某些内容,但您可以getInformation()在远程接口中实现一个方法;每个服务器对象都应该实现它并返回一个包含服务器对象所有信息的字符串。该方法通过从对象反射获取信息来生成字符串this