简体   繁体   English

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

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

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. 也获得返回值及其类型。

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: 或者使用varargs,如果您愿意:

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

(The above two calls are equivalent.) (以上两个电话相同。)

See the documentation for Method.invoke for more details. 有关更多详细信息,请参阅Method.invoke的文档。

simply create the object of MyClass invoke 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);

Try :: 尝试::

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM