Drools 无法将列表绑定到变量

Drools Can't bind a list to a variable

我有一个 returns 列表的函数。我试图在 drools when 子句中调用此函数并将其绑定到名为 l1 的变量。如果我像这样绑定变量,则子句不会执行。但是,如果我以类似的方式绑定地图,则执行 then 子句中的语句。 我正在使用最新版本的 drools。

这是代码

import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

dialect "java"

function Map<Integer, Integer> f1(){
  Map<Integer, Integer> h = new HashMap<>();
  h.put(1,2);
  h.put(2,6);
  return h;
}

function List<Integer> f2(){
  List<Integer> l = new ArrayList<>();
  l.add(1);
  l.add(2);
  return l;
}

rule "test1"
when
    $m1: Map() from f1()
then
    System.out.println("Inside test1");
    System.out.println($m1);
end

rule "test2"
when
    $l1: List() from f2()
then
    System.out.println("Inside test2");
    System.out.println($l1);
end

此处规则 'test1' 执行并打印值。但是我没有看到规则 'test2'.

的任何输出

如有任何帮助,我们将不胜感激。

您看到的行为是由 Drools 中的 from 运算符接受的特殊处理 Iterables 引起的。

在 Drools 中,您可以使用 from 运算符实际迭代 Iterable 并将左模式应用于其每个元素。例如,你可以这样做 像这样:

function List<String> getNames(){
  List<String> n = new ArrayList<>();
  n.add("John Doe");
  n.add("Peter Seller");
  n.add("John Wick");
  return n;
} 

rule "Filter Johns"
when
    $j: String(this matches "John.*") from getNames()
then
    System.out.println("John found: "+$j);
end

“Filter Johns”规则将执行 getNames() 函数,并将 String(this matches "John.*") 模式应用于函数返回的 List 中的每个元素。对于这种特殊情况,规则将被激活两次。

在您的示例中,因为 Map 不是 Iterable,所以 from 将左模式应用于它而不进行迭代。在您的第二条规则中,fc2() 函数被执行,from 检索带有 2 IntegersList 并将模式 List() 应用于它们中的每一个。当然,这不会引起任何激活。

在您的案例中查看此行为的一个明确方法是像这样修改您的第二条规则:

rule "test2"
when
    $l1: Object() from f2()
then
    System.out.println("Inside test2");
    System.out.println($l1);
end

在这种情况下,您会看到规则执行了两次。