19

I find myself constantly writing this statement

MyObject myObject = something.getThatObject();
if( myObject !=null &&
    myObject .someBooleanFunction()){

}

in order to prevent a null pointer exception. Is there a shortcut to this in Java? I'm thinking like myObject..someBooleanFunction()?

Carlos Bribiescas
  • 4,197
  • 9
  • 35
  • 66
  • I don't think Java does. Sadly. – But I'm Not A Wrapper Class May 29 '14 at 18:55
  • 1
    If only Oracle let the elvis operator into Java 7. – Mason T. May 29 '14 at 18:57
  • 1
    I don't think there is a way to make it shorter in Java but there are languages you can run on the JVM that support this kind of functionality. Groovy is fine example with its ["Elvis" and safe navigation operators](http://groovy.codehaus.org/Operators#Operators-ElvisOperator(?:)) So much for language features. As for making it shorter, take a look at `Optional` idioms in either Guava or Scala libraries. I believe Scala also has a neat syntax for it but I'm not familiar with it. – toniedzwiedz May 29 '14 at 18:58

4 Answers4

6

In Java 8:

static <T> boolean notNull(Supplier<T> getter, Predicate<T> tester) {
    T x = getter.get();
    return x != null && tester.test(x);
}

    if (notNull(something::getThatObject, MyObject::someBooleanFunction)) {
        ...
    }

If this style is new to the readers, one should keep in mind, that full functional programming is a bit nicer.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
4

Well Java 8 has got something called Optional. More details are at : http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html

jatanp
  • 3,982
  • 4
  • 40
  • 46
1

No, I am fairly sure that there is no way to do it any shorter than what you have.

Epiglottal Axolotl
  • 1,048
  • 8
  • 17
0

No if it is an object. String has isEmpty() but there is no built in way to check if an object is null other than what you have. This closed question has some comments that may help: why there is no isNull method in java object class

You could write your own in the class that would check null and your other method but it would have to be static or else you would run into your null pointer problem.

Community
  • 1
  • 1
ford prefect
  • 7,096
  • 11
  • 56
  • 83