目标很简单,我想创建一个动态加载类,访问其方法并传递参数值并在运行时获取返回值的方法。JAVA:调用未知对象类方法并传递它的参数
类将被称为
class MyClass {
public String sayHello() {
return "Hello";
}
public String sayGoodbye() {
return "Goodbye";
}
public String saySomething(String word){
return word;
}
}
主类
public class Main {
public void loadClass() {
try {
Class myclass = Class.forName(getClassName());
//Use reflection to list methods and invoke them
Method[] methods = myclass.getMethods();
Object object = myclass.newInstance();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().startsWith("saySome")) {
String word = "hello world";
//**TODO CALL OBJECT METHOD AND PASS ITS PARAMETER**
} else if (methods[i].getName().startsWith("say")) {
//call method
System.out.println(methods[i].invoke(object));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private String getClassName() {
//Do appropriate stuff here to find out the classname
return "com.main.MyClass";
}
public static void main(String[] args) throws Exception {
new Main().loadClass();
}
}
我的问题是如何调用方法与参数并传递它的价值?也获得了返回值及其类型。
+0
http://viralpatel.net/blogs/java-dynamic-class-loading-java-reflection-api/ –
+0
'System.out.println(methods [i] .invoke(object,word));' –