目標很簡單,我想創建一個動態加載類,訪問其方法並傳遞參數值並在運行時獲取返回值的方法。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();
}
}
我的問題是如何調用方法與參數並傳遞它的價值?也獲得了返回值及其類型。
http://viralpatel.net/blogs/java-dynamic-class-loading-java-reflection-api/ –
'System.out.println(methods [i] .invoke(object,word));' – assylias