java optional parameter in methods

I want to make a method that takes 1 required parameter and 1 optional parameter, but I found how to make an optional array which is by making in the parameter (int... b) but this is for an array, I want to make it just either this value is null or the user entered it, I can make it by making 2 methods of the same name but one with the single parameter and one with the 2 parameters, but can it be done with just one method?

Thanks


No, Java doesn't support optional parameters. Another alternative to overloading (which doesn't make much sense for two parameters but does make sense for more) is to use a builder type which represents all the parameters - you can provide a constructor for the builder which contains the required parameters, and then a setter for each of the optional ones, making the setter return the builder itself. So calling the method becomes something like:

foo.doSomething(new ParameterBuilder(10).setBar(2).setBaz(10));

What you are looking for is default arguments support. Java doesn't have this capability but it more or less simulates this capability.

One simple way is to use method overloading.

Another approach is to identify special cases directly and then substitute the default values.

Here's an example of mixing both of those approaches by Ivo Limmen:

public void test() {
   this.test(null, null);
}
public void test(String p1) {
   this.test(null, null);
}
public void test(String p1, String p2) {
   if(p1 == null) {
      ...
   } else {
      ...
   }
   if(p2 == null) {
      ...
   } else {
      ...
   }
}

A very interesting approach I found is to use Design Builder pattern. There is an example here

There is also an interesting discussion here


不,这正是重载的方法

链接地址: http://www.djcxy.com/p/20876.html

上一篇: 避免空值,不变性,对象状态

下一篇: 方法中的java可选参数