How to turn null into false in Java?

In my code I have a org.apache.tapestry5.json.JSONObject named j . I want to read the property use-name from that Object:

Boolean isUseName       = (Boolean) j.opt("use-name");

The value can either be true, false or null (if the entry is not present in the JSONObject). Now I'd like to use isUseName for a conditional statement:

if(!isUseName) {System.out.println("No Name to be used.")}

This gives me a NullPointerException if "use-name" was not in the JSONObject. One way is to simply check first if isUseName is null, eg

if(isUseName != null && !isUseName) {System.out.println("No Name to be used.")}

I was wondering, if there is a more elegant way. Is it eg possible to (automatically) set isUseName to false, if j.opt() returns null? One thing that came to my mind is using a ternary expression, but this has a redundant j.opt("use-name") :

Boolean isUseName = (j.opt("use-name") != null)
                  ? (Boolean) j.opt("use-name")
                  : false;

你可以用Boolean.TRUE进行比较:

boolean useName = Boolean.TRUE.equals (j.opt ("use-name"));

Logical expressions short-circuit, so if you check null first, then you can use it after the check:

if(isUseName != null && !isUseName) {
    // It's not null, and false
    System.out.println("No Name to be used.");
}

or

if(isUseName == null || !isUseName) {
    // It's null or false
    System.out.println("No Name to be used.");
}

and similarly

if(isUseName != null && isUseName) {
    // It's not null, and true
}

and

if(isUseName == null || isUseName) {
    // It's either null or true
}

如何检查密钥是否存在

boolean useName = j.has("use-name") ? j.getBoolean("use-name") : false;
链接地址: http://www.djcxy.com/p/76156.html

上一篇: 在java中如何检查null?

下一篇: 如何在Java中将null变成false?