Java spread operator

前端 未结 6 897
死守一世寂寞
死守一世寂寞 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:19

    If you need to call only few methods this way, you can do without Reflection simply by creating a wrapper class like this:

    Main class (SpreadTest.java):

    public class SpreadTest {
         public static void main(String []args){
            int[] a = {1, 2, 3};
            System.out.println(new FooWrapper().doSomething(a)); // 6
         } 
    }
    

    Your wrapper class (FooWrapper.java):

    public class FooWrapper extends Foo {
        public int doSomething(int ...a) {
            return super.doSomething(a[0], a[1], a[2]);
        }
    }
    

    The class with the method which does the work (Foo.java):

    public class Foo {
        public int doSomething(int a, int b, int c) {
            return a + b + c;
        }
    }
    

提交回复
热议问题