简体   繁体   English

Java谓词与嵌套对象的链接

[英]Java predicate chaining with nested object

private static final Predicate<Parent> HAS_SON = parent -> IS_CHILD(parent.getChild);
private static final Predicate<Child> IS_CHILD = Objects::nonNull;
private static final Predicate<Parent> IS_PARENT = Objects::nonNull;
private static final Predicate<Parent> IS_FATHER = IS_PARENT.and(HAS_SON);

I am trying to chain predicates, with one twist, and that is at one of predicate I want to use child object. 我试图一连串地链接谓词,那是我要使用子对象的谓词之一。

This is hypothetical situation I tried to make things easier for understanding. 这是我试图使事情更容易理解的一种假设情况。

  1. Call will be made to is_father ( parent ) 将会呼叫is_father( parent
  2. is_father will check if parent is not null is_father将检查parent是否为null
  3. and() has_son and()has_son
  4. has_son will call is_child (parent.getChild()) has_son将调用is_child(parent.getChild())
  5. is_child will check if child is not null is_child将检查child是否为null

There is a problem HAS_SON, I know syntax is not right, and may be nesting(parent.child) might not be allowed. HAS_SON有问题,我知道语法不正确,可能是nesting(parent.child)可能不允许。 Can some one please confirm? 可以请一个人确认吗? right now work around I am using is 现在我正在使用的解决方法是

private static final Predicate<Parent> HAS_SON = parent -> parent.getChild() != null;

Do not forget that a Predicate is triggered by using the test method of the FunctionalInterface . 不要忘记,通过使用FunctionalInterfacetest方法可以触发Predicate The following will work 以下将工作

private static final Predicate<Child> IS_CHILD = Objects::nonNull;
private static final Predicate<Parent> HAS_SON = parent -> IS_CHILD.test(parent.getChild);
private static final Predicate<Parent> IS_PARENT = Objects::nonNull;
private static final Predicate<Parent> IS_FATHER = IS_PARENT.and(HAS_SON);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM