You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hamcrest中CombinableMatcher组合匹配器的求值顺序是怎样的?

Hamcrest CombinableMatcher 链式调用求值顺序说明

你给出的链式调用会严格按照从左到右的调用顺序组合逻辑,最终等价的计算逻辑为 ((((matcher_1) AND matcher_2) OR matcher_3) AND matcher_4),不会遵循常规逻辑运算中「AND优先级高于OR」的规则。

原因解释

Java的方法调用是左结合的,每一次调用and()或or()方法,都是基于前一步已经生成的组合匹配器实例,再和新传入的匹配器做逻辑组合,你给出的代码可以拆解为四步执行:

  • 执行new CombinableMatcher<String>(matcher_1),得到封装了matcher_1的匹配器实例M1
  • 调用M1的and(matcher_2)方法,得到组合后的匹配器M2,等价逻辑为matcher_1 AND matcher_2
  • 调用M2的or(matcher_3)方法,得到组合后的匹配器M3,等价逻辑为(matcher_1 AND matcher_2) OR matcher_3
  • 调用M3的and(matcher_4)方法,得到最终匹配器,等价逻辑为(((matcher_1 AND matcher_2) OR matcher_3) AND matcher_4)

实现高优先级AND的写法

如果你想要得到((matcher_1 AND matcher_2) OR (matcher_3 AND matcher_4))的逻辑,需要先把优先级更高的AND组合单独封装为独立的匹配器,再做外层OR组合,参考写法:

// 先封装两个优先级更高的AND逻辑块
CombinableMatcher<String> leftPart = new CombinableMatcher<String>(matcher_1).and(matcher_2);
CombinableMatcher<String> rightPart = new CombinableMatcher<String>(matcher_3).and(matcher_4);
// 再组合两个块的OR逻辑
CombinableMatcher<String> finalMatcher = leftPart.or(rightPart);

内容的提问来源于stack exchange,提问作者Number945

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 23:21:03