public void printStrings(String... strings) {
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); }
Jonathon faust
source share