I'm not quite proficient in Java, so I would like to know if I'm doing right here.
As the title states, the code below is for getting some default reply when fetching an attribute on a null object, or an object with a null attribute value.
this seems to work, but I'd be thankful if someone could tell me if I'm looking at the problem the right way.
import java.util.Optional;
import java.util.function.Function;
public class ReplyOnNullPointer {
static class C{
private String a;
public C(String a){this.a=a;}
public String getAtt(){return a;}
}
private static<I,R> R getterWithDefault(I o,Function<? super I,R> mapper, R orDefault){
return Optional.ofNullable(o).flatMap(x->Optional.ofNullable(mapper.apply(x))).orElse(orDefault);
}
public static void main(String[] args) {
C o1 = null;
C o2 = new C(null);
C o3 = new C("attribut");
System.out.println("o3 : "+o3);
System.out.println("o3.att : "+o3.getAtt());
System.out.println();
System.out.println("o2 : "+o2);
System.out.println("o2.att : "+o2.getAtt());
System.out.println("o2.att : "+Optional.of(o2).flatMap(x->Optional.ofNullable(x.getAtt())).orElse("<nope>"));
System.out.println();
System.out.println("o1 : "+o1);
System.out.println("o1.att : "+Optional.ofNullable(o1).flatMap(x->Optional.ofNullable(x.getAtt())).orElse("<nope>"));
System.out.println();
System.out.println("o1.att : "+getterWithDefault(o1,C::getAtt,"<nope>"));
System.out.println("o2.att : "+getterWithDefault(o2,C::getAtt,"<nope>"));
System.out.println("o3.att : "+getterWithDefault(o3,C::getAtt,"<nope>"));
}
}
the ouput looks like this :
o3 : ReplyOnNullPointer$C@15db9742
o3.att : attribut
o2 : ReplyOnNullPointer$C@6d06d69c
o2.att : null
o2.att : <nope>
o1 : null
o1.att : <nope>
o1.att : <nope>
o2.att : <nope>
o3.att : attribut
thanks for your corrections/opinions/advices
I think it's just:
Optional.ofNullable(o).map(mapper).orElse(orDefault);
You don't need flatMap(x->Optional.ofNullable(mapper.apply(x)))
, this is exactly what chaining map
on Optional
is doing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.