I have a method which takes key and its associated parameters in the following format.
public String foo(String key, Object[] parameters) {..}
I would prefer to pass the parameters using a variable argument format. How should I do that?
I tried public String foo(String key, Object... parameters) {..}
- But this seems to collide with the method definition given above.
Should I do something like the fo开发者_Go百科llowing and wrap this into the Object[] method?
public String foo(String key, Object a) {..}
public String foo(String key, Object a, Object b) {..}
public String foo(String key, Object a, Object b, Object c) {..}
Just change the definition of the existing function to
public String foo(String key, Object... parameters) {..}
The variadic method mechanism in Java is syntactic sugar for creating an array at the call site and passing it in. So this method should be compatible with existing source code and compiled classes.
From the Java documentation on varargs:
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.
Give the method a different name:
public String bar(String key, Object... a) {
return foo(key, a);
}
The name should be close to the original one, probably specifying the reason why it exists (but this can be documented as well). I can't be more specific with "foo" :)
This is of course needed if you can't change the existing method signature, for example inheriting from a 3rd party class. If you can change it - change it. Old invocations will still work.
public String foo(String key, Object[] parameters)
and public String foo(String key, Object... parameters)
are the same methods, their ("class file") signatures are equivalent.
If you have a method like
public String foo(String key, Object... parameters) {}
the follwing calls are allowed:
foo("1", obj1);
foo("2", obj1, obj2);
foo("3", new Object[]{obj1, obj2, obj3});
public String foo(String key, Object[] parameters) {..}
and
public String foo(String key, Object... parameters) {..}
are equal
精彩评论