我正在使用 RMI 允许通过在另一个 JVM 中运行的 MATLAB 访问我的 Java 应用程序。 MATLAB 有一个很好的接口(interface)来打印 Java 对象的方法。但它在 RMI 中失败了,因为它获取的对象是一个代理。
所以我想添加我自己的方法来提取/打印远程接口(interface)的能力(RMI 显然不能直接访问在导出的远程接口(interface)中不可用的方法)。
我如何通过反射在 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 中的示例客户端 session
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
最佳答案
客户端上的对象是代理:它们被称为 stub 。要从它获取接口(interface),您应该编写类似这样的代码,其中 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);
}
stub 是自动生成的:因此您不应该在其中实现某些东西,但您可以在远程接口(interface)中实现方法 getInformation()
;每个服务器对象都应该实现它并返回一个包含服务器对象所有信息的字符串。此方法通过从 this
对象反射获取信息来生成字符串。
关于java - RMI + java 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3839815/