Thursday, 14 May 2009

Null Check for Java Bean Properties

I was trying to find out an easy way to check nulls in my Java Bean. There is this filter screen where I need to throw an Exception if all the properties are blank. This is required so that the database don't get hit with "Search All" query. I used BeanUtils from Apache Commons to get all the properties and StringUtils to check if the property is blank. Here is a snippet of the code that I used:


.
.
.
Map<String, String> map = BeanUtils.describe(searchCriteria);
boolean allBlank = true;
if (map != null) {
for (String key : map.keySet()) {
if ("class".equalsIgnoreCase(key) || "metaClass".equalsIgnoreCase(key))
continue;
if (StringUtils.isNotBlank(map.get(key))) {
LOG.info("key " + key + " is not null");
allBlank = false;
break;
}
}
}
if (allBlank) {
throw new IllegalArgumentException("searchCriteria cannot be blank"));
}
.
.
.

2 comments:

  1. nice post, boss ! Anyway, please be kind to share some of your java basic knowledge :)

    ReplyDelete