I have some constructors like these where I must handle with parameters being null
.
public Element(int value1, String value2, String value3, String value4) {
this.value1 = value1;
this.value2 = value2 != null ? value2 : "";
this.value3 = value3 != null ? value3 : "";
this.value4 = value4 != null ? value4 : "";
}
Yes I know, I could write a utility-method or my own annotation to reduce the boiler plate code for params 2,3,4
But is there any existing solution? Something like @DefaultOnNull("")
on the parameter or even the class?
Thanks for all comments. I solved it this way to reduce the boiler plate code at least a little bit:
public Element(int value1, String value2, String value3, String value4) {
this.value1 = value1;
this.value2 = Objects.requireNonNullElse(value2, "");
this.value3 = Objects.requireNonNullElse(value3, "");
this.value4 = Objects.requireNonNullElse(value4, "");
}
You can use below code
this.value2 = StringUtils.defaultString(value2);
StringUtils is an Apache commons library and is widely used and standard library for String related operations. Maven - https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.10
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.