【问题标题】:Generic method calling using java reflection api使用java反射api调用通用方法
【发布时间】:2015-04-16 10:33:37
【问题描述】:

我一直在尝试开发一个应用程序。将根据要求编写一个 bean 脚本,然后根据要求以各种顺序调用方法(在应用程序中定义)。应用程序代码(除了 bean 脚本)不会改变。

此外,该应用程序使用提供大量方法的外部 jar,其中一些在应用程序中实现。但是,如果需要,我希望有可能使用其他方法(尚未实现的方法)而无需更改应用程序。为此,我想使用 Java 反射 API。用户应该能够通过传递方法名称和相应的参数(使用外部 jar 文档)来调用外部 jar 中存在的任何方法。

我是 java 新手,所以我有一些代码试图实现它(可能在语法上不正确):

public void callExternalJarMethod(String methodName, Class[] methodParameterTypes, Object[] methodParameters) 
throws NoSuchMethodException { 

String className = "SampleClassName"; 
Class classObject = Class.forName(className); 
Method methodObject;

    if (methodParameterTypes.length == 0) {
        methodObject = classObject.getMethod(methodName, null);
    } else {        
        methodObject = classObject.getMethod(methodName, methodParameterTypes);         
    } 

    // Not handling calling of static methods in which case "null" would be passed instead of methodObject to the invoke method
    Object returnValue = methodObject.invoke(methodObject, methodParameters);
}   

我正在尝试找到一种方法,可以让 Class[] methodParameterTypes 和 Object[] methodParameters 填充相关值。我将参数类型和参数值作为字符串。此外,任何指向有用工具的指针都将不胜感激。

提前致谢。

【问题讨论】:

  • 那么,参数类型和值是什么?
  • 由于是通用的,参数类型可以是Integer、String等可能的(类型)参数。参数值将是从字符串(输入)类型转换为相应参数类型的实际值。
  • 您不能简单地将Strings 投射 到任意类。
  • 感谢费边。不知道。

标签: java reflection


【解决方案1】:

您没有将 SampleClassName 的实例传递给此处的 Method.invoke() 调用...

Object returnValue = methodObject.invoke(methodObject, methodParameters);

如果你要调用的方法是static,你可以这样做...

Object returnValue = methodObject.invoke(null, methodParameters);

否则(非静态),您需要创建一个 SampleClassName 的实例来执行该方法。

如果类不需要任何构造函数参数,您可以使用...

Object returnValue = methodObject.invoke(classObject.newInstance(), methodParameters);

(显然会有很多异常需要通过“newInstance”和“invoke”来处理...)

【讨论】:

  • 不太确定这是否真的是一个关于泛型的问题,它更像是一个反射 API ......
  • 谢谢布雷特。很抱歉造成混淆 - 问题不在于泛型。我的意思是泛型,试图传达我可能必须调用的方法可能会有所不同,并且可以采用各种参数,例如 String、Int 等。
猜你喜欢
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
相关资源
最近更新 更多