null时获取空字符串 [英] Get empty string when null

查看:164
本文介绍了null时获取空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取字段的字符串值(它们可以是长字符串或任何对象的类型),

I want to get string values of my fields (they can be type of long string or any object),

如果字段为空,则应返回空字符串,我用guava做了这个;

if field is null than it should return empty string, I did this with guava;

nullToEmpty(String.valueOf(gearBox))
nullToEmpty(String.valueOf(id))
...

但如果变速箱为空,则返回null!不是空字符串,因为valueOf methdod返回字符串null,这会导致错误。

But this returns null if gearbox is null! not empty string because valueOf methdod returns string "null" which leads to errors.

任何想法?

EDIt :有100个字段我寻找易于实现的东西

EDIt: there are 100s fields I look for something easy to implement

推荐答案

你可以使用 Objects.toString() (Java 7中的标准):

You can use Objects.toString() (standard in Java 7):

Objects.toString(gearBox, "")

Objects.toString(id, "")






来自链接文档:


From the linked documentation:


public static String toString(Object o,String nullDefault)


返回调用 toString 的结果在第一个参数上,如果第一个参数不为null,否则返回第二个参数。

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

参数:

o - 一个对象

nullDefault - 如果第一个参数是,则返回字符串null

Parameters:
o - an object
nullDefault - string to return if the first argument is null

返回:

调用 toString <的结果/ code>关于第一个参数,如果它不是 null ,否则是第二个参数。

Returns:
the result of calling toString on the first argument if it is not null and the second argument otherwise.

另请参阅:

toString(Object)


这篇关于null时获取空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆