Skip to content

Use Commons Lang

by Jeff

A snippet of code I see a lot is this:

if(a != null && a.equals(b)) {
  //do something
}

One of the handy methods that Commons Lang gives you is:

ObjectUtils.equals(a, b) where either a or b or both can be null and you
don’t have to worry about those pesky null checks. Another useful one is
ObjectUtils.toString(a). If a is null it returns a blank string.

Here’s another one:

//a is a string
if(a == null || "".equals(a)) {
  //do something
}

You can use one of these instead:

StringUtils.isBlank(a),
StringUtils.isNotBlank(a), StringUtils.isEmpty(a),
StringUtils.isNotEmpty(a).

There’s also a toString builder, and equalsBuilder and a hashCode builder
and each of those can grab all the fields via reflection.

Of course, you’ll have to check out the api docs to see if any of these
methods work in the situation you have, but for the most part they are
very handy.

http://jakarta.apache.org/commons/lang/

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*