Java Unpack Lists

Here's another question: "How do I do this in Java?" In Python, I can use the "*" character to unpack the arguments as follows:

>>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5] 

Java supports getting an argument list with the syntax ...args , but is there a way (possibly using the Reflection libraries?) To unpack them for some other function?

+4
java reflection
source share
2 answers
 public void printStrings(String... strings) { // the strings parameter is really a String[]. // You could do anything to it that you normally // do with an array. for(String s : strings){ System.out.println(s); } } 

You can call it like this:

 String[] stringArray = new String[10]; for(int i=0; i < stringArray.length; i++){ stringArray[i] = "String number " + (i+1); } printStrings(stringArray); 

Syntax ... is really syntactic sugar for arrays.

There is no tool in Java that you describe, but you can fake it in several ways.

I think coming closer means overloading any function that you want to use in this module using varargs.

If you have a method:

 public void foo(int a, String b, Widget c) { ... } 

You can overload it:

 public void foo(Object... args) { foo((Integer)args[0], (String)args[1], (Widget)args[2]); } 

But it is really awkward and error prone and hard to maintain.

More generally, you can use reflection to invoke any method using any arguments, but it also received a ton of traps. Here's a buggy, incomplete example of how it gets ugly really fast:

 public void call(Object targetInstance, String methodName, Object... args) { Class<?>[] pTypes = new Class<?>[args.length]; for(int i=0; i < args.length; i++) { pTypes[i] = args[i].getClass(); } Method targetMethod = targetInstance.getClass() .getMethod(methodName, pTypes); targetMethod.invoke(targetInstance, args); } 
+5
source share

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

The hard part, through reflection, finds the correct method (well, it is easy if there is only one method with the same name, otherwise it is very difficult).

Cost - additional time for searching / calling a method.


Of course, if you know a specific method at compile time, you can handle this manually, for example. here for a function with three arguments:

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

All Articles