Reputation: 1647
can we give @QueryParam of type boolean a default value null ? if yes, how do we do it?
this is how I tried to do it but I still get false as default value:
@POST
public String setMethod(
@QueryParam("value1") @DefaultValue("null") Boolean value1)
Upvotes: 4
Views: 2841
Reputation: 1538
I am facing the same problem, and unfortunately there isn't a direct way to solve this.
Sadly, we can't use enums because @RequestParam defaultValue
and switch-case need a constant. It also can't automatically map it from "null" into the enum.
@POST
public String setMethod(
@QueryParam("value1") @DefaultValue("null") String value1)
Boolean boolValue1 = null;
switch(value1) {
case "true":
boolValue1 = Boolean.TRUE;
break;
case "false":
boolValue1 = Boolean.FALSE;
break;
default:
break;
}
Since there isn't a case for null
, it should remain null.
Upvotes: 4
Reputation: 3314
You should try without DefaultValue
. As value1
is not a primitive it should stay null
.
So like this :
@POST
public String setMethod(
@QueryParam("value1") Boolean value1)
following the spec:
If @DefaultValue is not used in conjunction with @QueryParam, and the query parameter is not present in the request, the value will be an empty collection for List, Set, or SortedSet; null for other object types; and the default for primitive types.
Regarding your example --> new Boolean("null")
is actually equals to false
.
So the result is normal.
BTW
: Null should not be a valid option as a Boolean is a binary value either 0 or 1. Once it crosses into the tri-state (null, false, true) it's no longer a true Boolean and maybe if it is acceptable preferable to switch to enum value.
What about something like this ?
public enum Value {
A ,
B,
ABSENT
}
@POST
public String setMethod(
@QueryParam("value1") @DefaultValue("ABSENT") Value value1)
Upvotes: 2