Java unpacking argument lists

后端 未结 2 1750
灰色年华
灰色年华 2021-02-20 10:40

Here\'s another question of \"How would I do this in Java?\" In Python, I can use the \'*\' symbol to unpack arguments like so:

>>> range(3, 6)                  


        
2条回答
  •  深忆病人
    2021-02-20 10:52

    If the function you're calling is not a varargs function (declared with ...) then you do need to use reflection. Method.invoke() takes an array Object[] of arguments.

    The tough part via reflection is finding the right method (well, it's easy if there's only one method with the same name, otherwise it's very difficult).

    The cost is the extra time to lookup/invoke the method.


    Of course, if you know the specific method at compile-time, then you can deal with this manually, e.g. here for a 3-argument function:

    Object[] args = /* get args from somewhere */
    callSomeNonVarargsFunction((Cast1)args[0], (Cast1)args[1], (Cast1)args[2]);
    

提交回复
热议问题