jonnyB_5531
jonnyB_5531

Reputation: 191

Java: Does Java converts method arguments to array under the hood?

I'm trying to understand reflection and currently digging on how to call an instance method when you only have its name as string. For this reason invoke from java.lang.reflect.Method can be used. What bothers me is its signature invoke(Object obj, Object... args) where the first argument is an instance on which the method will be invoked and the second argument is just array of arguments for method invocation. In case of reflection passing arguments as array is the only option since invoke can invoke method with arbitrary num of arguments. What is really interesting to me is the same thing happens when you call the method directly(without reflection), are arguments also converted to array ? E.g. I have such method void foo(int x, String s, Bar bar) in my FooClass and if I call foo in regular manner new FooClass().foo(7, "HelloWorld", new Bar()) would Java under the hood convert all those three arguments to array as well, or array with argument is only used when you invoke method using reflection ?
Thank you

Upvotes: 2

Views: 86

Answers (1)

luk2302
luk2302

Reputation: 57174

No, creating an array from the arguments would cause far too much overhead. The array is only used in the invoke situation because ... what else is there to do? How would you design a method that can be called with an arbitrary amount of objects and types? Your only option is the varargs Object... args. (other than a direct array, making calling it more cumbersome or overloads for e.g. calling it with 1, 2, 3, ... arguments)

Upvotes: 2

Related Questions