【问题标题】:RMI + java reflectionRMI + java反射
【发布时间】:2010-10-01 13:54:10
【问题描述】:

我使用 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;        
}

以及 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

【问题讨论】:

    标签: java reflection rmi


    【解决方案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);
    }
    

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

    【讨论】:

    • 啊,getClass().getInterfaces() 方法是我所缺少的。不知何故,我认为您必须 getInterfaces() 不获取类对象。
    • 你不需要让服务器来实现这个。客户端可以在他的存根上运行完全相同的代码并得到相同的答案。
    • 7 年后,EJP 给了我一个可接受的答案 -2 并重写它以获得积分,但确实希望我拥有它。哈哈!太棒了!请删除我的f*答案!!!!!!
    猜你喜欢
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 2011-06-26
    • 1970-01-01
    • 2010-10-17
    • 2010-09-30
    • 2011-11-01
    相关资源
    最近更新 更多