Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

null-safe的toString方法 #12

Open
vonzhou opened this issue Nov 6, 2019 · 0 comments
Open

null-safe的toString方法 #12

vonzhou opened this issue Nov 6, 2019 · 0 comments

Comments

@vonzhou
Copy link
Owner

vonzhou commented Nov 6, 2019

在开发过程中,把对象转换为字符串的场景很常见,但是直接调用对象的toString方法,是可能会抛出NPE的,所以会有很多类似下面的模板代码。

String str = a == null ? "" : a.toString();

其实有很多常用的工具包中都提供了null-safe的工具方法,这里列举下。

JDK自带

其实最简单也最容易被忽略的是 String.valueOf() 方法。

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

JDK 1.7之后引入的Objects工具中也有:

public static String toString(Object o) {
        return String.valueOf(o);
    }

public static String toString(Object o, String nullDefault) {
        return (o != null) ? o.toString() : nullDefault;
    }

commons-lang中StringUtils

public static String toString(Object obj) {
        return obj == null ? "" : obj.toString();
    }

public static String toString(Object obj, String nullStr) {
        return obj == null ? nullStr : obj.toString();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant