Is there Java syntax for specifying zero or a single value passed to a method?

So, I found that we have a three-point notation for zero or more, but is there anything for zero or one?

I need to change the method, not overload it. I was wondering if there is a syntax to just allow null or single value?

public void test(String sample, ObjectMapper... argOm){
    ObjectMapper om = (!argOm.equals(null)?argOm:new ObjectMapper());
}

This does not do what I want, as it expects []. I just want zero or one.

Does it overload the only way besides changing all the links to it?

+4
source share
3 answers

, , . , Java , " " .

, :

public void test(String sample){
    test(sample, new ObjectMapper());
}
public void test(String sample, ObjectMapper om){
    if (om == null) {
        throw new IllegalArgumentException("object mapper");
    }
    ...
}

, , , , .

+6

:

public void test(String sample) {
    test(sample, new ObjectMapper());
    ...
}
public void test(String sample, ObjectMapper argOm) {
    ObjectMapper om;
    if (argOm != null)
        om = argOm;
    ...
}

ObjectMapper. 1 , .

+5

, , , . , Builder Pattern :

class Foo {
     private final String sample; 
     private final ObjectMapper objectMapper = new ObjectMapper();

     private Foo(String sample, ObjectMapper objectMapper) {
        this.sample = sample;
        if (objectMapper != null) {
           this.objectMapper = objectMapper;
        }
     }

     public static class Builder {
        private final String sample; 
        private final ObjectMapper objectMapper;

        public Builder sample(String sample) {
            this.sample = sample;
            return this;
        }

        public Builder objectMapper(ObjectMapper objectMapper) {
            this.objectMapper = objectMapper;
            return this;
        }

        public Foo build() {
            return new Foo(sample, objectMapper);
        }
     }
 }

:

Foo.Builder
   .sample(mySample)
   .objectMapper(myObjectMapper)
   .build()

:

Foo.Builder
   .sample(mySample)
   .build()

. , , , , , , , , , , .

+3

Source: https://habr.com/ru/post/1671628/


All Articles