如何检查一个字符串既不是 null
也不是空的?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
如何检查一个字符串既不是 null
也不是空的?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
public boolean isEmpty(String testString) {
return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}
public class StringUtils {
static boolean anyEmptyString(String ... strings) {
return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
}
}
例子:
public String concatenate(String firstName, String lastName) {
if(StringUtils.anyBlankString(firstName, lastName)) {
throw new IllegalArgumentException("Empty field found");
}
return firstName + " " + lastName;
}
为了检查对象中是否所有的字符串属性都为空(而不是使用Java反射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;
}
如果所有字符串字段的值都为空,则此方法将返回true;如果任何一个值存在于字符串属性中,则返回false。
处理字符串中的 null 更好的方法是:
str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()
str.length()>0 && !str.equalsIgnoreCase("null")
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
...
}
PreparedStatement
等代替通过字符串连接原语构建 SQL 查询。这样可以避免各种注入漏洞,而且更易读等。 - polygenelubricantsPredicate.<String>isEqual(null).or(String::isEmpty).negate()
,具体解释请参考这里。 - Alexander Ivanchenko