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();
    }
}

我的问题是如何使用参数调用方法并传递其值?还获取返回值及其类型。

4

3 回答 3

4

我认为你只是错过了这样一个事实,即你可以将参数传递给invoke, 作为Object[]

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

或使用可变参数,如果您愿意:

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

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

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

于 2012-12-10T07:20:16.233 回答
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);
于 2012-12-10T07:18:31.267 回答
0

尝试 ::

Class c = Class.forName(className); 
Method m = c.getDeclaredMethod(methodName, params);
Object i = c.newInstance();
String result = (String)m.invoke(i, args);
于 2012-12-10T07:19:46.247 回答