We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
在开发过程中,把对象转换为字符串的场景很常见,但是直接调用对象的toString方法,是可能会抛出NPE的,所以会有很多类似下面的模板代码。
String str = a == null ? "" : a.toString();
其实有很多常用的工具包中都提供了null-safe的工具方法,这里列举下。
其实最简单也最容易被忽略的是 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; }
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(); }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
在开发过程中,把对象转换为字符串的场景很常见,但是直接调用对象的toString方法,是可能会抛出NPE的,所以会有很多类似下面的模板代码。
其实有很多常用的工具包中都提供了null-safe的工具方法,这里列举下。
JDK自带
其实最简单也最容易被忽略的是 String.valueOf() 方法。
JDK 1.7之后引入的Objects工具中也有:
commons-lang中StringUtils
The text was updated successfully, but these errors were encountered: