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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13796536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:00:56  来源:igfitidea点击:

JAVA: Calling Unknown Object Class Method and Passing it's Parameters

javaobjectmethodsparametersinstance

提问by Angga Saputra

The objective is simple, I want to create a method which load a class dynamically, access its method and passing their parameters value and getting the return value at run-time.

目标很简单,我想创建一个动态加载类的方法,访问它的方法并传递它们的参数值并在运行时获取返回值。

Class which will be called

将被调用的类

class MyClass {

    public String sayHello() {

        return "Hello";
    }

    public String sayGoodbye() {

        return "Goodbye";
    }

    public String saySomething(String word){
        return word;
    }
}

Main Class

主班

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

My question is how to invoke method with parameters and passing its value? also getting the return value and its type.

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

采纳答案by Jon Skeet

I think you're just missing the fact that you can pass in arguments to invoke, as an Object[]:

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

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

Or using varargs, if you prefer:

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

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

(The above two calls are equivalent.)

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

See the documentation for Method.invokefor more details.

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

回答by Murali Prasanth

simply create the object of MyClassinvoke the function like this

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

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

or do this

或者这样做

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

回答by Sashi Kant

Try ::

尝试 ::

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