Wednesday, February 24, 2010

Smart Way of Doing Null Checks for JAXBElements

If want to Avoid using if(X!=null){a = x.toString}else{"NULL"}; many times in code, this blog is usefull to you.
I got a situation like : To track the data passed to a webservice, i need to create a large string which has values of the number of inputs passed to a webmethod.As all the input elements are JAXB elements and most of the input elements are optional, I must have to do a null check to each and every element before converting it to string.For this i created a small method as follows:
private String JAXBNullHandler(JAXBElement obj) { if (obj != null) { return String.valueOf(obj.getValue()); } else { return "NULL"; } }Wherever i need the string value of an element i used the method call as follows:
JAXBNullHandler(amount); where amount is a JAXBElement.
This has reduced a considerable amount of code and the code is legible.

No comments:

Post a Comment