Does Java support default parameter values?

后端 未结 25 1621
清歌不尽
清歌不尽 2020-11-22 07:07

I came across some Java code that had the following structure:

public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}         


        
相关标签:
25条回答
  • 2020-11-22 07:14

    No.

    You can achieve the same behavior by passing an Object which has smart defaults. But again it depends what your case is at hand.

    0 讨论(0)
  • 2020-11-22 07:14

    It is not supported in java as in other language for ex. Kotlin.

    0 讨论(0)
  • 2020-11-22 07:14

    One idea is to use String... args

    public class Sample {
       void demoMethod(String... args) {
          for (String arg : args) {
             System.out.println(arg);
          }
       }
       public static void main(String args[] ) {
          new Sample().demoMethod("ram", "rahim", "robert");
          new Sample().demoMethod("krishna", "kasyap");
          new Sample().demoMethod();
       }
    }
    

    Output

    ram
    rahim
    robert
    krishna
    kasyap
    

    from https://www.tutorialspoint.com/Does-Java-support-default-parameter-values-for-a-method

    0 讨论(0)
  • 2020-11-22 07:18

    There are half a dozen or better issues such as this, eventually, you arrive at the static factory pattern ... see the crypto API for that. Sort difficult to explain, but think of it this way: If you have a constructor, default or otherwise, the only way to propagate state beyond the curly braces is either to have a Boolean isValid; ( along with the null as default value v failed constructor ) or throw an exception which is never informative when getting it back from field users.

    Code Correct be damned, I write thousand line constructors and do what I need. I find using isValid at object construction - in other words, two-line constructors - but for some reason, I am migrating to the static factory pattern. I just seem you can do a lot if you in a method call, there are still sync() issues but defaults can be 'substituted' better ( safer )

    I think what we need to do here is address the issue of null as default value vis-a-vis something String one=new String(""); as a member variable, then doing a check for null before assigning string passed to the constructor.

    Very remarkable the amount of raw, stratospheric computer science done in Java.

    C++ and so on has vendor libs, yes. Java can outrun them on large scale servers due to it's a massive toolbox. Study static initializer blocks, stay with us.

    0 讨论(0)
  • 2020-11-22 07:20

    You may use Java Method Invocation Builder to automatically generate the builder with default values.

    Just add @GenerateMethodInvocationBuilder to the class, or interface, and the @Default to parameters in methods where you want default values. A builder will be generated at compile time, using the default values that you specified with your annotations.

    @GenerateMethodInvocationBuilder
    public class CarService {
     public CarService() {
     }
    
     public String getCarsByFilter(//
       @Default("Color.BLUE") Color color, //
       @Default("new ProductionYear(2001)") ProductionYear productionYear,//
       @Default("Tomas") String owner//
     ) {
      return "Filtering... " + color + productionYear + owner;
     }
    }
    

    And then you can invoke the methods.

    CarService instance = new CarService();
    String carsByFilter = CarServiceGetCarsByFilterBuilder.getCarsByFilter()//
      .invoke(instance);
    

    Or set any of the default values to something else.

    CarService instance = new CarService();
    String carsByFilter = CarServiceGetCarsByFilterBuilder.getCarsByFilter()//
      .withColor(Color.YELLOW)//
      .invoke(instance);
    
    0 讨论(0)
  • 2020-11-22 07:21

    It is not supported but there are several options like using parameter object pattern with some syntax sugar:

    public class Foo() {
        private static class ParameterObject {
            int param1 = 1;
            String param2 = "";
        }
    
        public static void main(String[] args) {
            new Foo().myMethod(new ParameterObject() {{ param1 = 10; param2 = "bar";}});
        }
    
        private void myMethod(ParameterObject po) {
        }
    }
    

    In this sample we construct ParameterObject with default values and override them in class instance initialization section { param1 = 10; param2 = "bar";}

    0 讨论(0)
提交回复
热议问题