How to unpack an array into different arguments on method call

后端 未结 3 1194
误落风尘
误落风尘 2021-02-14 02:31

I would like to know if it is possible to unpack an Object array into separate Object on method call which accepts vargs. This question is similar to this one.

I have a

3条回答
  •  忘掉有多难
    2021-02-14 03:21

    This does not implement the Unpack solution, instead it goes about it by making an overload method as I said in my comment. I do not know if this at all what you wanted, but I got it to work and I felt like I would post this for reference.

    public class Test {
        public static Object doWork(Object... objects){
            System.out.println(objects.length);
            return objects;
        }
    
        // this is the method that will concatenate the arrays for you
        public static Object doWork(Object[] objects1, Object... objects2){
            System.out.println(objects1.length + "+" + objects2.length);
            Object[] retval = new Object[objects1.length+objects2.length];
            System.arraycopy(objects1, 0, retval, 0, objects1.length);
            System.arraycopy(objects2, 0, retval, objects1.length, objects2.length);
            return retval;
        }
    
        public static void main(String[] args){
            Object res = doWork("one", "two");
            res = doWork((Object[])res, "three");
            Object[] res2 = (Object[])res; // = {one, two, three}
        }
    }
    

提交回复
热议问题