简体   繁体   English

将参数动态传递到Method.Invoke

[英]Passing parameters dynamically into Method.Invoke

I have methods in a class 我在课堂上有方法

public class ReflectionClass {
    public int add(int a, int b) {
        return a + b;
    }
    public int add(int a, int b, int c) {
        return a + b + c;
    }
    public String concatenate (String a, String b, String c){
        return a + b + c;
    }
}

I'm trying to call these methods through reflection. 我试图通过反思来调用这些方法。 All I have in hand are - the method name and the parameters. 我手头的所有内容都是 - 方法名称和参数。 Is there a way to pass the parameters into the Method.Invoke() method dynamically based on the number/type of parameters I have in hand? 有没有办法根据我手头的参数数量/类型动态地将参数传递给Method.Invoke()方法?

正如你在docs中看到的那样, public Object invoke(Object obj, Object... args)接受一个varargs参数 - 所以你可以简单地传递一个参数数组。

You need to create an instance, get the methods, get the parameters, check the parameters by checking the type and how many... then call invoke depending of what 你需要创建一个实例,获取方法,获取参数,通过检查类型和数量检查参数...然后根据什么调用调用

Example: 例:

public static void main(String[] args) throws Exception {
    Class<?> cls = Class.forName("com.ReflectionClass");
    Object obj = cls.newInstance();
    for (Method m : cls.getDeclaredMethods()) {
        if (m.getParameterCount() == 3 && Arrays.asList(m.getParameterTypes()).contains(String.class)) {
            String a = "A";
            String b = "B";
            String c = "C";
            Object returnVal = m.invoke(obj, a, b, c);
            System.out.println((String) returnVal);
        } else if (m.getParameterCount() == 2 && Arrays.asList(m.getParameterTypes()).contains(int.class)) {
            int a = 5;
            int b = 3;
            Object returnVal = m.invoke(obj, a, b);
            System.out.println(returnVal);
    } else if (m.getParameterCount() == 3 && Arrays.asList(m.getParameterTypes()).contains(int.class)) {
            int a = 5;
            int b = 3;
            int c = 3;
            Object returnVal = m.invoke(obj, a, b, c);
            System.out.println(returnVal);
    }
}
}

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

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