user496949 user496949 - 2 years ago 86
Java Question

Any simple way to test null before convert an object to string

I always write

Object o;
if (o!=null)
String s = o.toString();

If there simple way to handle this case?

Answer Source

ObjectUtils.toString(object) from commons-lang. The code there is actually one line:

return obj == null ? "" : obj.toString();

Just one note - use toString() only for debug and logging. Don't rely on the format of toString().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download