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

Drools如何校验List存储的Java对象的字符串属性是否为指定值

错误原因

你原有规则的写法存在语法错误,Drools会将Premium($insuranceTypes : InsuranceType(name == 'TPD'))解析为访问Premium类下名为InsuranceType的属性的name字段,但Premium类中仅存在insuranceTypes的List<InsuranceType>属性,不存在对应的name字段,因此抛出找不到方法的报错。

正确实现方式

你可以通过from语法遍历Premium的insuranceTypes列表,配合exists判断是否存在符合条件的元素,规则写法如下:

rule "rule#3"
when
    $fact: Premium($insuranceTypes: insuranceTypes)
    exists InsuranceType(name == "TPD") from $insuranceTypes
then
    System.out.println("Error");
end

如果你需要在规则后果中拿到匹配到的InsuranceType对象做后续处理,可以直接绑定匹配到的对象:

rule "rule#3"
when
    $fact: Premium($insuranceTypes: insuranceTypes)
    $matchedInsurance: InsuranceType(name == "TPD") from $insuranceTypes
then
    // 可直接使用$matchedInsurance变量操作匹配到的对象
    System.out.println("Error,匹配到的险种名称:" + $matchedInsurance.getName());
end

注意事项

  • 请确保Premium类提供getInsuranceTypes()公共 getter 方法,InsuranceType类提供getName()公共 getter 方法,Drools默认通过 getter 方法访问类的私有属性。
  • 如果insuranceTypes列表为空,上述规则不会触发,符合你"存在符合条件元素才触发"的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:36:04