In Eclipse (4.7.2) with null analysis -> potential null access set to give me a warning.
Given the following code:
public class Test {
// validator method
static boolean hasText(String s) {
return !(s == null || s.trim().isEmpty());
}
public static void main(String[] args) {
// s could come from anywhere and is null iff the data does not exist
String s = (new Random().nextBoolean()) ? "valid" : null;
if (hasText(s)) {
// Potential null pointer access: The variable s may be null at this location
System.out.println(s.length());
// ... do actual stuff ...
}
}
}
how can I avoid the potential null warning? @NotNull won't work since null is a valid input and the output is a boolean.
Is there a way to tell the compiler that if this validation method returns true then the validated value was non-null?
Is there some better way to handle validation methods like this?
Thanks.
Update for clarity:
The data comes from user input (from xml or .properties file) and will be null iff the data does exist.
Never producing null (eg. setting it to "") would be inventing data that does not exist, and I can't exactly have a NullString object (can't extend String) to represent non-existent data.
hasText(String s) must be able to accept any of this input data and thus must be able to accept null.
hasTextis a String - not a null. And you're trying to pass thenullinstead ofStringcallingString s = (new Random().nextBoolean()) ? "valid" : null;Try to writeString s = (new Random().nextBoolean()) ? "valid" : "";Optional<String> mayBeNull;?(s == null || s.trim().isEmpty()) ? false : trueis just longhand for!(s == null || s.trim().isEmpty()), ors != null && !s.trim().isEmpty().