【发布时间】: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