[英]java 8 getter with default value on null object or attribute
I'm not quite proficient in Java, so I would like to know if I'm doing right here. 我不太熟悉Java,所以我想知道我是否在这里做。
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. 正如标题所述,下面的代码用于在获取空对象或具有null属性值的对象时获取某些默认回复。
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. 你不需要
flatMap(x->Optional.ofNullable(mapper.apply(x)))
,这正是Optional
上的链接map
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.