我想在drools中收集一些项目作为键-值对,但我不能修改现有的java代码,我必须通过drools中的一个规则来实现。
**when**
// I know it's collected as a list, but this is what I want to modify in my code and I don;t know how
$myList : List() from accumulate(MyClass($myclassId: id,
$myClassValue : value), collectList($$myclassId + " " + $myClassValue))
我想在 then 子句中用它作为哈希值,我知道它是一个列表,但我不知道收集它作为哈希值的语法,把它作为一个哈希[id] -> 值。
规则是这样的:**when**/ I ...
import java.util.List;
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;
import accumulate org.droolsassert.MapAccumalateFunction collectMap;
rule X
when
$list: List()
$numberTypes: Map() from accumulate (
$elem: Number() from $list,
collectMap(new SimpleEntry($elem.intValue(), $elem.getClass()))
)
then
System.out.println('collected: ' + $numberTypes);
end
积累功能
public class MapAccumalateFunction implements AccumulateFunction<HashMap<Object, Object>> {
@Override
public void writeExternal(ObjectOutput out) throws IOException {
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
@Override
public HashMap<Object, Object> createContext() {
return new HashMap<>();
}
@Override
public void init(HashMap<Object, Object> context) throws Exception {
}
@Override
public void accumulate(HashMap<Object, Object> context, Object value) {
Entry<Object, Object> entry = (Entry<Object, Object>) value;
context.put(entry.getKey(), entry.getValue());
}
@Override
public void reverse(HashMap<Object, Object> context, Object value) throws Exception {
}
@Override
public Object getResult(HashMap<Object, Object> context) throws Exception {
return context;
}
@Override
public boolean supportsReverse() {
return false;
}
@Override
public Class<?> getResultType() {
return null;
}
}
检验
@DroolsSession(resources = "classpath:/test.drl")
public class PlaygroundTest {
@Rule
public DroolsAssert drools = new DroolsAssert();
@Test
public void testIt() {
drools.insertAndFire(asList(new Integer(1), new AtomicInteger(2), new BigDecimal(3)));
}
}
测试输出
00:00:00 --> inserted: Arrays.ArrayList[a={1,2,3}]
00:00:00 --> fireAllRules
00:00:00 <-- 'X' has been activated by the tuple [ArrayList, HashMap]
collected: {1=class java.lang.Integer, 2=class java.util.concurrent.atomic.AtomicInteger, 3=class java.math.BigDecimal}