当方法具有变量arglist时的Java反射

Gin*_*ray 5 java reflection

我有以下几点:

public class A { 
    public void theMethod(Object arg1) {
        // do some stuff with a single argument
    }
}

public class B {
    public void reflectingMethod(Object arg) {
        Method method = A.class.getMethod("theMethod", Object.class);
        method.invoke(new A(), arg);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何修改它以便我可以执行以下操作?

public class A { 
    public void theMethod(Object... args) {
        // do some stuff with a list of arguments
    }
}

public class B {
    public void reflectingMethod(Object... args) {
        Method method = A.class.getMethod("theMethod", /* what goes here ? */);
        method.invoke(new A(), args);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ran*_*ggs 5

A.class.getMethod("theMethod", Object[].class);
Run Code Online (Sandbox Code Playgroud)


Gin*_*ray 0

一旦我开始思考如何去做,达特尼厄斯在原始问题的评论中的建议就奏效了。

public class A {
    public void theMethod(ArrayList<Object> args) { // do stuff 
    }
}

public class B {
    public void reflectingMethod(ArrayList<Object> args) {
        Method method;
        try {
            method = A.class.getMethod("theMethod", args.getClass());
            method.invoke(new A(), args);
        } catch (Exception e) {}
    }
}
Run Code Online (Sandbox Code Playgroud)