我需要比较同一类的对象

时间:2013-09-12 21:16:42

标签: java object jboss drools business-rules

我需要在一个规则drools中比较同一类的两个对象。但是,我怎么知道一个属性属于在主类中创建的对象?我需要帮助!

public class CheckerMain {

    public static void main(String[] args) {
        try {
            KnowledgeBase kbase = readKnowledgeBase();
            StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
            KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "ConflictChecker");

            DeonticConcept deoCon1 = new DeonticConcept("forbidden");        
            DeonticConcept deoCon2 = new DeonticConcept("permission");

            ksession.insert(deoCon1);
            ksession.insert(deoCon2);

            ksession.fireAllRules();
            logger.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    private static KnowledgeBase readKnowledgeBase() throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add(ResourceFactory.newClassPathResource("Rules.drl"), ResourceType.DRL);
        KnowledgeBuilderErrors errors = kbuilder.getErrors();
        if (errors.size() > 0) {
            for (KnowledgeBuilderError error: errors) {
                System.err.println(error);
            }
            throw new IllegalArgumentException("Could not parse knowledge.");
        }
        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
        return kbase;
    }
}

我想在一个规则中比较对象deoCon1和deoCon2中的属性nameConceptDeontic。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

我想你问,“我如何确定instanceFoo的课程?”但语法难以破译。

如果是,请使用instanceof运算符。在您的情况下,instanceFoo将是属性的父对象:

if (instanceFoo instanceof classBar){
    //do stuff
}

或者您可以尝试getClass()方法,http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html

详细说明

答案 1 :(得分:0)

这样的东西?

rule "..."
when
    $dc1: DeonticConcept()
    $dc2: DeonticConcept(this != $dc1, nameConceptDeontic == $dc1.nameConceptDeontic)
then
    ...
end

请注意,以上内容将激活两次。对于1& 2和对于2& 1。如果您需要阻止这种情况,您可能希望阻止第二次激活。一种方法是插入一个MatchedConcepts事实并添加一个不存在这样一个事实的附加约束。