简体   繁体   中英

Optional parameter in java (can be null)

I have a function with a boolean parameter, but it could be null too.

If it's true or false, it makes a query with a "WHERE" clause. If it was null, the query has no "WHERE" clause, only the select clause.

How can I do that in Java ?

Use Boolean class

public String foo(Boolean addWhere){
    String query = "SELECT * FROM tbl";
    if(addWhere != null){
        query += (addWhere? " WHERE true" : " WHERE false");
    }
    return query;
}

Call it as following,

String q = foo(false);

You can use java.lang.Boolean; this is the wrapper class for primitive boolean. The value can be null, Boolean.TRUE or Boolean.FALSE, but due to auto-unboxing you can also directly compare with true and false.

There are several ways to do so:

  • Declaring two functions, one with a boolean parameter and one without a parameter.
  • Declaring one function with an Optional<Boolean> parameter.
  • Declaring one funktion with a Boolean parameter, where null is the unspecified case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM