Skip to main content

Posts

Showing posts with the label variableargumentlists

Invoking variable-arity methods with Java reflection?

I would like to understand what might be going on with invoking variable-arity methods using Java reflection. Let's say we have a simple method: void doAllTheThings(Object ... things) { // ...which does something with all the things... } And we want to invoke it dynamically, so we grab the method through reflection: Method doItAll = Superklass.getDeclaredMethod("doAllTheThings", Object[].class); And pass in an array: Object[] allTheThings = new Object[] { "abc", true, 15 }; doItAll.invoke(allTheThings); Now, this doesn't seem to work quite like my intuition had figured; in particular, I seem to be getting various shades of IllegalArgumentException when I try invoking a method with varargs like this. There's clearly something I'm missing here. My guess is this is related somehow to how the variables get marshalled into the varargs. I've found this four year old blog post which seems to be talking about the same issue , but am unable