I use object != null
a lot to avoid NullPointerException.
Is there a good alternative to this?
For example I often use:
Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections
Example:
String foo;
...
if( StringUtils.isBlank( foo ) ) {
///do something
}
or (depending on what you need to check):
String foo;
...
if( StringUtils.isEmpty( foo ) ) {
///do something
}
The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.
Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)
public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
return read(new StringReader(xml), true, validationEventHandler);
}
And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)
Example on how to use this static classf from spring(org.springframework.util.Assert)
Assert.notNull(validationEventHandler,"ValidationHandler not Injected");