我已将用户定义类中的对象添加到 HashMap 中。当插入到 Drools 代码中时,我可以遍历 HashMap 并获取键值对。但是我无法访问用户类内部的属性,这是 HashMap 的值部分。
这是用于保存数据的 POJO 文件。此 POJO 将使用单独的键插入到 LinkedHashMap 中。目前,这个 key 只是使用一个简单的 for 循环生成的。
package com.sample.pojos;
import java.util.Date;
public class DateSet {
public DateSet() {
// TODO Auto-generated constructor stub
super();
}
public DateSet(String trainingType, Date completedDate, Date expirationDate) {
super();
this.trainingType = trainingType;
this.completedDate = completedDate;
this.expirationDate = expirationDate;
}
private String trainingType;
private Date completedDate;
private Date expirationDate;
public String getTrainingType() {
return trainingType;
}
public void setTrainingType(String trainingType) {
this.trainingType = trainingType;
}
public Date getCompletedDate() {
return completedDate;
}
public void setCompletedDate(Date completedDate) {
this.completedDate = completedDate;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
}
这是用于向 LinkedHashMap 添加值的 Java 代码。我使用了 LinkedHashMap,因为我需要以正确的顺序访问项目。 HashMap 的键是一个 int,而值将是一个 DateSet 对象。
outHash.put(incrementedId, new DateSet(training.getTrainingType(), training.getCompletionDate(),
training.getExpirationDate()));
这是我用来处理 HashMap 的 Drools 规则。代码中的注释部分是我想如何在 Drools 中使用该对象。 “entry.getValue()”打印 DateSet 对象,但我无法访问其中的属性。
rule "Validate test"
agenda-group "validate_init"
when
someClass: SomeClass($tMap : outHash)
entry : Entry($valueV : value) from $tMap.entrySet()
//Boolean(booleanValue == true) from ($valueV.getTrainingType() == "NEW")
then
//System.out.println($valueV.getTrainingType());
System.out.println(entry.getKey() + "-" + entry.getValue());
end
最佳答案
这条规则做我认为你想要的(版本 6.3.0):
rule "Validate test"
when
SomeClass($tMap : outHash)
e: Map.Entry(k:key, v:value) from $tMap.entrySet()
DateSet( tt: trainingType == "NEW" ) from v
then
System.out.println(e.getKey() + "-" + tt);
end
但是,有人想知道您为什么不将 DateSet 对象作为单独的事实插入,这使得访问和过滤变得非常容易。人工编号 (incrementedId) 不是数据的一部分,那么它的用途是什么?
编辑 如果您需要将一个 DateSet 对象与下一个对象进行比较(按日期排序),您应该向 DateSet 添加一个序号属性并插入 DateSet 对象。然后:
rule "check for overdue training"
when
$ds1: DateSet( $ord1: ordinal, $exp: expirationDate )
$ds2: DateSet( ordinal == $ord1+1, completedDate > $exp )
then
// ds2 is too late
end
她的技巧是属性 ordinal
使您能够选择连续的 DateSet 对象对(因为它们是按日期创建和编号的):它将第一个与第二个进行比较,第二个与第三,依此类推。 - 您可以添加 trainingType == "NEW"
或类似内容以供进一步选择。
关于java - Drools 在迭代时访问 HashMap 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33645469/