Java spread operator

前端 未结 6 901
死守一世寂寞
死守一世寂寞 2021-01-01 10:11

I am not sure of the vocabulary I am using here, please correct me if I\'m wrong.

In Javascript, I had the following code:

let args = [1,2,3];

func         


        
6条回答
  •  死守一世寂寞
    2021-01-01 10:24

    Java language does not provide an operator to do this, but its class library has a facility to do what you need.

    [from OP's comment] The developer of Foo could choose himself the number of arguments that function doSomething takes. I would then be able to construct a "bag" of arguments and inject it in the method.

    Use reflection API, this is what it is for. It requires you to package arguments in an array. There is a lot of extra work required, including wrapping/unwrapping individual method arguments, and method result, but you can check the signature at run-time, construct an array, and call the method.

    class Test {
        public static int doSomething(int a, int b, int c) {
            return a + b + c;
        }
        // This variable holds method reference to doSomething
        private static Method doSomethingMethod;
        // We initialize this variable in a static initialization block
        static {
            try {
                doSomethingMethod = Test.class.getMethod("doSomething", Integer.TYPE, Integer.TYPE, Integer.TYPE);
            } catch (Exception e) {
            }
        }
        public static void main (String[] ignore) throws java.lang.Exception {
            // Note that args is Object[], not int[]
            Object[] args = new Object[] {1, 2, 3};
            // Result is also Object, not int
            Object res = doSomethingMethod.invoke(null, args);
            System.out.println(res);
        }
    }
    

    The above code prints 6 (demo).

提交回复
热议问题