Access to Drools returned fact object in Java Code

早过忘川 提交于 2019-12-06 10:21:31

(Note: I fixed the order of statement, a typo ("XX") and removed the comments from the output. Less surprise.)

This snippet assumes that EligibilityInquiry is also declared in DRL.

FactType eligInqFactType = ruleBase.getFactType("mortgages", "EligibilityInquiry");
Class<?> eligInqClass = eligInqFactType.getFactClass();
ObjectFilter filter = new FilterByClass( eligInqClass );
Collection<Object> eligInqs = workingMemory.getObjects( filter );

And the filter is

public class FilterByClass implements ObjectFilter {
    private Class<?> theClass;
    public FilterByClass( Class<?> clazz ){
        theClass = clazz;
    }
    public boolean accept(Object object){
        return theClass.isInstance( object );
    } 
}

You might also use a query, which takes about the same amount of code.

// DRL code
query "eligInqs" 
    eligInq : EligibilityInquiry()
end

// after return from fireAllRules
QueryResults results = workingMemory.getQueryResults( "eligInqs" );
for ( QueryResultsRow row : results ) {
    Object eligInqObj = row.get( "eligInq" );
    System.out.println( eligInqClass.cast( eligInqObj ) );
}

Or you can call workingMemory.getObjects() and iterate the collection and check for the class of each object.

for( Object obj: workingMemory.getObjects() ){
    if( obj.isInstance( eligInqClass ) ){
        System.out.println( eligInqClass.cast( eligInqObj ) );
    }
}

Or you can (with or without inserting the created EligibilityInquiry object as a fact) add the fact to a global java.util.List eligInqList and iterate that in your Java code. Note that the API of StatefulKnowledgeSession is required (instead of WorkingMemory).

   // Java - prior to fireAllRules
   StatefulKnowledgeSession kSession() = ruleBase.newStatefulSession();

   List<?> list = new ArrayList();
   kSession.setGlobal( "eligInqList", list );

   // DRL
   global java.util.List eligInqList;

   // in a rule
   then
       EligibilityInquiry fact0 = new EligibilityInquiry(); 
       fact0.setServiceName( "ABCD" ); 
       fact0.setMemberStatus( true ); 
       insert(fact0 );  
       eligInqList.add( fact0 ); 
   end

   // after return from fireAllRules
   for( Object elem: list ){
    System.out.println( eligInqClass.cast( elem ) );
   }

Probably an embarras de richesses.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!