如何检查字符串是否为非空?

public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty string */
    }
    /* ... */
}

当前回答

java-11中有一个新方法:String#isBlank

如果字符串为空或只包含空白代码点则返回true,否则返回false。

jshell> "".isBlank()
$7 ==> true

jshell> " ".isBlank()
$8 ==> true

jshell> " ! ".isBlank()
$9 ==> false

这可以与Optional结合起来检查字符串是否为null或空

boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);

字符串#是空白

其他回答

检查对象中的所有字符串属性是否为空(而不是按照java reflection api方法对所有字段名使用!=null)

private String name1;
private String name2;
private String name3;

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this) != null) {
                return false;
            }
        } catch (Exception e) {
            System.out.println("Exception occurred in processing");
        }
    }
    return true;
}

如果所有String字段值为空,此方法将返回true;如果String属性中存在任何一个值,则返回false

使用Java 8可选,你可以做:

public Boolean isStringCorrect(String str) {
    return Optional.ofNullable(str)
            .map(String::trim)
            .map(string -> !str.isEmpty())
            .orElse(false);
}

在这个表达式中,您也将处理由空格组成的字符串。

如果你使用Spring框架,那么你可以使用method:

org.springframework.util.StringUtils.isEmpty(@Nullable Object str);

该方法接受任何Object作为参数,将其与null和空String进行比较。因此,对于非空的非string对象,此方法永远不会返回true。

如何:

if(str!= null && str.length() != 0 )

你可以使用函数式检查:

Optional.ofNullable(str)
    .filter(s -> !(s.trim().isEmpty()))
    .ifPresent(result -> {
       // your query setup goes here
    });