Java 如何比较谓词

Java how to compare Predicates

我有两个产品:

Predicate<CategoryModel> predicate1 = NavigationCategoryModel.class::isInstance;
Predicate<CategoryModel> predicate2 = BrandCategoryModel.class::isInstance;

使用 if 语句,如何确定我使用的是哪个谓词?我正在尝试做这样的事情,但显然没有编译:

if(predicate1.equals(NavigationCategoryModel.class::isInstance)){
}

if(predicate1==NavigationCategoryModel.class::isInstance){
}

有什么提示吗?我对 Java 8 个 lambdas

很陌生

这是 Pojos 的代码(用于测试目的的简单继承):

public class CategoryModel {
}

public class NavigationCategoryModel  extends CategoryModel{
}

public class BrandCategoryModel extends CategoryModel {
}

您应该对谓词使用 test 方法。而且,你必须提供对象来执行验证而不是实际的方法引用

predicate.test(object)

文档:Predicate#test

对于您的问题,您可以测试当对象的类型为 NavigationCategoryModel 时 predicate1 returns 是否为真,如下所示:

predicate1.test(new NavigationCategoryModel()) // returns true

同样,对于BrandCategoryModel,使用:

predicate2.test(new BrandCategoryModel()) // returns true

如果你想测试对象匹配两个中的任何一个,你可以像这样组合两个谓词:

predicate1.or(predicate2).test(new NavigationCategoryModel()) // returns true
predicate1.or(predicate2).test(new BrandCategoryModel()) // returns true

您尝试的是找到您使用的实现。

唯一的方法是使用 Predicate 中的函数 test

true if the input argument matches the predicate, otherwise false
public static void main(String args[]) {

    Predicate<CategoryModel> predicate1 = NavigationCategoryModel.class::isInstance;
    Predicate<CategoryModel> predicate2 = BrandCategoryModel.class::isInstance;

    System.out.println("Predicate1 isNavigation: " + isNavigation(predicate1));
    System.out.println("Predicate1 isBrand: " + isBrand(predicate1));
    System.out.println("--------------------------------------------------");
    System.out.println("Predicate2 isNavigation: " + isNavigation(predicate2));
    System.out.println("Predicate2 isBrand: " + isBrand(predicate2));

}

public static boolean isNavigation(Predicate<CategoryModel> predicate){

    return predicate.test(new NavigationCategoryModel());

}

public static boolean isBrand(Predicate<CategoryModel> predicate){

    return predicate.test(new BrandCategoryModel());

}

和昆仑的方案一样,不过我觉得你应该多加一个条件,比如

Predicate<CategoryModel> predicate1 = NavigationCategoryModel.class::isInstance;
Predicate<CategoryModel> predicate2 = BrandCategoryModel.class::isInstance;

Predicate<CategoryModel> predicate1Testing = NavigationCategoryModel.class::isInstance;

System.out.println("Is A NavigationCategoryModel Predicate? " + predicate1.and(predicate1Testing).test(new NavigationCategoryModel()));