How can I create a method which takes one or more optional parameters?
Arvind Prabhakar In my knowledge, there is no special construct in Java language that allows for passing optional parameters. However, there are some workarounds that are worth considering:
- Use of Collections: In most cases, certain types of collections may be used for passing in a list of objects that are actually the optional parameters. The drawback with this approach is that you will have to use objects to represent your optional parameters - which means that for every case where you want to pass a primitive type, you will have to pass the corresponding wrapper like java.lang.Integer for a normal int argument. The advantages you have with this approach are many. You could have ordered collections indicating the order of the parameters passed if that is of any significant consequence to your application. You could have Map constructs that associate descriptive keys to the arguments, which may help provide extra information to process these parameters and so on.
- Lazy Method Invocation: This is a much less known strategy which involves the repetitive calls to secondary helper methods to set the state of the object, followed by the actual method call with no arguments whatsoever. So you could call the setArgument(Object arg) method as many times as you want (or any other specialized strain of this method), before calling the method that will deal with all these arguments.