JAVA: 调用未知对象类方法并传递参数

4
目标很简单,我想创建一种方法,在运行时动态加载类,访问其方法并传递参数值,并获取返回值。
将要被调用的类:
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/ - Markus Lausberg
System.out.println(methods[i].invoke(object, word)); - assylias
3个回答

4

我认为你可能忽略了一个重要的事实,就是你可以通过Object[]将参数传递给invoke方法:

Object result = methods[i].invoke(object, new Object[] { word });

或者使用可变参数,如果您喜欢的话:
Object result = methods[i].invoke(object, word);

(以上两个调用是等效的。)

有关更多详细信息,请参见Method.invoke的文档。


是的,我的错误。methods[i].invoke 的第二个参数是用于传递参数的。谢谢 Jon。 - Angga Saputra

1

只需创建MyClass对象,像这样调用函数

MyClass mc = new MyClass();
String word = "hello world";
String returnValue = mc.saySomething(word);
System.out.println(returnValue);//return hello world here

或者这样做

Class myclass = Class.forName(getClassName());
Method mth = myclass.getDeclaredMethod(methodName, params);
Object obj = myclass.newInstance();
String result = (String)mth.invoke(obj, args);

0

尝试 ::

Class c = Class.forName(className); 
Method m = c.getDeclaredMethod(methodName, params);
Object i = c.newInstance();
String result = (String)m.invoke(i, args);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接