Java reflection when a method has an arglist variable

I have something like the following:

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

How can I change this so that I can do the following instead?

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);
    }
}
+5
source share
2 answers

Dartenius's suggestion in the comments on the original question worked as soon as I turned my head around how to do this.

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) {}
    }
}
0
source
A.class.getMethod("theMethod", Object[].class);
+5
source

All Articles