开发者

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

开发者 https://www.devze.com 2023-02-21 19:40 出处:网络
I always write Object o; i开发者_StackOverflow社区f (o!=null) String s = o.toString(); If there simple way to handle this case?The static valueOf method in the String class will do the null check a

I always write

Object o;
i开发者_StackOverflow社区f (o!=null)
String s = o.toString();

If there simple way to handle this case?


The static valueOf method in the String class will do the null check and return "null" if the object is null:

String stringRepresentation = String.valueOf(o);


Try Objects.toString(Object o, String nullDefault)

Example:

import java.util.Objects;

Object o1 = null;
Object o2 = "aString";
String s;

s = Objects.toString(o1, "isNull"); // returns "isNull"
s = Objects.toString(o2, "isNull"); // returns "aString"


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().


Updated answer of Bozho and January-59 for reference:

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

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

However this method in Apache Commons is now deprecated since release 3.2 (commons/lang3). Their goal here was to remove all the methods that are available in Jdk7. The method has been replaced by java.util.Objects.toString(Object) in Java 7 and will probably be removed in future releases. After some discussion they did not remove it yet (currently in 3.4) and it is still available as a deprecated method.

Note however that said java 7+ method will return "null" for null references, while this method returns and empty String. To preserve behavior use

java.util.Objects.toString(myObject, "")


import java.util.Objects;
Objects.toString(object, "")

Simple and 0 runtime exception :)


String.valueOf(o) returns the string "null" if o is null.

Another one could be String s = o == null? "default" : o.toString()


You can use java 8 Optional in the following way:

String s = Optional.ofNullable(o).map(Object::toString).orElse("null");


Depending on what you want it to on a null value but you can just do this

Object o =
String s = ""+o;

This is the default behaviour for println and string append etc.


It looks like you want get a String when o is not a NULL. But I'm confusing that if coding like yours you can't access variable s (you know s in scope of if statement).

0

精彩评论

暂无评论...
验证码 换一张
取 消