我使用trim()方法来修剪一些字符串字段中的前导和尾随空格.

siteRequest.getName().trim();

然而,当字符串字段为null时,它会按预期引发异常.我可以在修剪前判断值,如下所示:

siteRequest.getName() ? siteRequest.getName() : siteRequest.getName().trim();

然而,如果可能的话,我更喜欢一种更干净的方式,这样一些人就已经面临这个问题了.有什么更明智的建议吗?

推荐答案

我喜欢@Sebastiaan van den Broek的 idea ,但不想使用图书馆,因此请查阅implementation:

// Trim
//-----------------------------------------------------------------------
/**
 * <p>Removes control characters (char &lt;= 32) from both
 * ends of this String, handling {@code null} by returning
 * {@code null}.</p>
 *
 * <p>The String is trimmed using {@link String#trim()}.
 * Trim removes start and end characters &lt;= 32.
 * To strip whitespace use {@link #strip(String)}.</p>
 *
 * <p>To trim your choice of characters, use the
 * {@link #strip(String, String)} methods.</p>
 *
 * <pre>
 * StringUtils.trim(null)          = null
 * StringUtils.trim("")            = ""
 * StringUtils.trim("     ")       = ""
 * StringUtils.trim("abc")         = "abc"
 * StringUtils.trim("    abc    ") = "abc"
 * </pre>
 *
 * @param str  the String to be trimmed, may be null
 * @return the trimmed string, {@code null} if null String input
 */
public static String trim(final String str) {
    return str == null ? null : str.trim();
}

在我看来,没有更好的方法来实施它.使用Optionals不是一个选项.因此,问题的原始解决思路得到了确认.

Java相关问答推荐

在没有maven或IDE的情况下从命令行运行PFA模块化应用程序时出现神秘错误

将状态栏和导航栏设置为白色,带有深色文本

替换com. sun. jndi. dns. DnsContextFactory Wildfly23 JDK 17

在Java Stream上调用collect方法出现意外结果

无法在org. openjfx:javafx—fxml:21的下列变体之间进行 Select

调用引发泛型异常的泛型方法时出现编译错误

如何找到MongoDB文档并进行本地化?

蒙蒂霍尔比赛结果不正确

计算两个浮点数之间的距离是否对称?

自定义批注的外推属性值

使用OAuth 2.0资源服务器JWT时的授权(授权)问题

基于接口的投影、原生查询和枚举

Kotlin Val是否提供了与Java最终版相同的可见性保证?

SpringBoot:在条件{Variable}.isBlank/{Variable}.isEmpty不起作用的情况下进行路径变量验证

如何创建模块信息类文件并将其添加到JAR中?

无法使用Freemarker从XML中读取重复的标记值

try 使用类来包含JSON响应

寻找Thread.sky()方法的清晰度

java.lang.ClassCastException:com.google.firebase.FirebaseException无法转换为com.google.fire base.auth.FirebaseAuthException

javax.crypto-密码对象-提供者服务是如何工作的?