Question

I need compare two objects of the same class in one rule drools. But, how I can know that one atribute belongs to object created in main class? I need help!

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;
    }
}

I want compare the atribute nameConceptDeontic instanced in objects deoCon1 and deoCon2 in one rule. How I can do this?

Was it helpful?

Solution

I think you're asking, "How can I determine instanceFoo's class?" but the grammar is hard to decipher.

If so, use the instanceof operator. In your case, instanceFoo will be the attribute's parent object:

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

Or you can try the getClass() method, which is explained in detail at http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html

OTHER TIPS

Something like this?

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

Note that the above will activate twice. For 1&2 and for 2&1. If you need to prevent that, you may wish to block a second activation. One way to do this would be to insert a MatchedConcepts fact and add an additional constraint that such a fact does not exist.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top