3

I have a Class structure such as

 Class A {
     int val;
  }

 Class B {
   A a;
 }

 Class C {
   B b;
 }

Now, all the classes are from a third party service, from which I get a response and I want to read the int value. But i dont want to do something like

lets assume c is a variable of type C.

if (c != null && c.getb != null) {
 B b = c.getb()
  and so on.
 }

I want to avoid these null checks as in reality these pojos are very hierarchical and have a lot of fields in them.

I tried using

Optional<Integer> val = Optional.ofNullable(c.getb().geta().getval());
val.elseThrow(Ex::new)

but this is not the right approach as (it throws null pointer exception if b is not present as optional is on int). What can i do to tackle such a situation where i don't have control over the declarations of Pojos but want to avoid bull checks?

Crosk Cool
  • 664
  • 2
  • 12
  • 27

1 Answers1

6

You can use map

int val = Optional.ofNullable(c)
                  .map(x -> x.getb())
                  .map(x -> x.geta())
                  .map(x -> x.getval())
                  .getOrThrow(Ex::new);

You can use method references if you know the class name. e.g.

int val = Optional.ofNullable(c)
                  .map(C::getb)
                  .map(B::geta)
                  .map(A::getval)
                  .getOrThrow(Ex::new);

This works as map will call the function once if the value if it's not null, otherwise the result is also null. i.e. any null value falls through the chain of map calls to the end.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130