Issue
I'm working on an API (Eclipse IDE - Kepler), JDK 1.7) I need a shortcut like @IfNotNullUpdate
consider the following e.g.
Model model = new Model();
String field1 = entity.getField1() != null ? entity.getField1() : "";
model.setField1(field1);
so that I can simply write it like
model.setField1( @IfNotNullUpdate entity.getField1(),"");
I don't want to have any NullPointerExceptions. It will be a great help If it can work like builder pattern. for e.g.
model.addField_25(@IfNotNullUpdate entity.getField_37())
.addField_16(@IfNotNullUpdate entity.getField_69());
I tried @NonNull of lombok. It just ensures that param is not null which is not my requirement.
And of-course assert() can't be a solution. Hope I'm able to explain my requirement well.
Thanks in advance.
Solution
Have a look at Optional
. Using the sample provided, the following can throw a NPE if any of the methods called returns a null value:
String version = computer.getSoundcard().getUSB().getVersion();
To avoid that or excessive if (x != null)
checks, using Optional
you can use:
String name = computer.flatMap(Computer::getSoundcard)
.flatMap(Soundcard::getUSB)
.map(USB::getVersion)
.orElse("UNKNOWN");
Answered By - M. Shaw
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.