Java Reflection and RMI



在我的应用程序中使用以下代码。有人能对突出显示的代码给出详细解释吗?

我知道在第一个突出显示的块中,java反射用于调用handle_validation方法。。但需要详细说明。

然后在第二个突出显示的块中抛出RemoteException。。

我的确切问题是,他们为什么使用反射来调用EngineHandlerIF,然后为什么在这个EngineHandlerF中使用RMI来调用EngineHandler中方法的定义?

private static EngineHandlerIF init() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "validation.xml" });
        String[] beans = ctx.getBeanDefinitionNames();
        for (String string : beans) {
            logger.info(string);
        }
        EngineHandlerIF engine = (EngineHandlerIF) ctx.getBean("engine");
        return engine;
    }

private Object callEngineMethod(MiddlewareMessage mmsg) {
        Object resultObj;
        try {
            **String methodName = "handle_validation";
            Method method = EngineHandlerIF.class.getDeclaredMethod(methodName, MiddlewareMessage.class);
            method.setAccessible(true);
            resultObj = method.invoke(engine, new Object[] { mmsg });**
        } catch (Exception e) {
            logger.error("sendMessage Exception: ", e);
            return new Boolean(false);
        }
        return resultObj;
    }
EngineHandlerIF:
----------------
**public abstract String handle_validation(MiddlewareMessage mmsg) throws RemoteException;**
EngineHandler:
--------------
public String handle_validation(MiddlewareMessage mmsg) throws Exception {
//some code
    }

我知道在第一个突出显示的块中使用了java反射在调用handle_validation方法时。。但需要详细的解释

差不多了。唯一的其他部分是

 method.setAccessible(true);

这使得调用者可以访问该方法(例如从private到public),从而允许您调用它。然而,上面的方法似乎已经是public了。也许这是重构后的遗留问题?

请注意,这不是RMI(远程方法调用),而是反射。我在这里看到的唯一RMI是可能抛出RemoteExceptionhandle_validation()方法。

也许有人刚刚发现了反射的锤子,所以所有的东西,包括已经公开的方法,都开始看起来像个疯子。

这是垃圾:扔掉。只需直接调用该方法。

最新更新