+-

我想获取我的字段的字符串值(它们可以是长字符串或任何对象的类型),
如果一个字段为null,那么它应该返回空字符串,我用guava做了这个;
nullToEmpty(String.valueOf(gearBox))
nullToEmpty(String.valueOf(id))
...
但是如果变速箱为空,则返回null!不是空字符串,因为valueOf methdod返回字符串“null”,这会导致错误.
有任何想法吗?
EDIt:有100个字段我寻找易于实现的东西
最佳答案
您可以使用
Objects.toString()(Java 7中的标准):
Objects.toString(gearBox, "")
Objects.toString(id, "")
从链接的文档:
public static String toString(Object o, String nullDefault)Returns the result of calling
toStringon the first argument if the first argument is not null and returns the second argument otherwise.Parameters:
o– an object
nullDefault– string to return if the first argument isnullReturns:
the result of callingtoStringon the first argument if it is notnulland the second argument otherwise.See Also:
07001
点击查看更多相关文章
转载注明原文:java – null时获取空字符串 - 乐贴网