It may not be a good idea to use a wrapper class from java.lang for
collecting results from rule execution. Setting and retrieving a
global is simple, as suggested by Frank and Esteban:
Double d1 = new java.lang.Double(0);
ksession.setGlobal("result", d1 );
// execute the session
Double d2 = (Double)ksession.setGlobal("result" );
But how do you add something to your result? You might think that this is it:
rule "not a good idea"
when
... $x ...
then
result += $x;
end
But this isn't going to work, because the Double is made available as a
local copy. To update the global, you'll have to use something like
kcontext.getKnowledgeRuntime().setGlobal( "result", result+$x );
It would be better to write a simple class, call it Sum, with a field
double value and a getter and a setter, and then you can do
Sum s = new Sum();
ksession.setGlobal("result", s );
// execute the session
double result = s.getValue(); // the reference is still good
And the rule uses
then
result.setValue( result.getValue() + $x );
end
or add a convenience method plus(double d) to Sum
then
result.plus( $x );
end
-W
On 15/01/2013, Esteban Aliverti <esteban.aliverti(a)gmail.com> wrote:
After you fireAllRules() you can get latest value of the global
using:
Double result = (Double) ksession.getGlobal("result");
Best Regards,
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Esteban Aliverti
- Blog @
http://ilesteban.wordpress.com
On Tue, Jan 15, 2013 at 10:20 AM, FrankVhh
<frank.vanhoenshoven(a)agserv.eu>wrote:
> java.lang.Double result = new java.lang.Double(0);
> ksession.setGlobal("result", result);
>
> ?
>
>
> penny wrote
> > test.java file:
> >
> > KnowledgeBase kbase = readKnowledgeBase();
> > StatefulKnowledgeSession ksession =
> > kbase.newStatefulKnowledgeSession();
> > ksession.setGlobal("result", new java.lang.Double(0));
> >
> >
> > I have used the global variable “result” in the rule file,how to use it
> in
> > the test.java file?
> > I need a judgement like “if(result>0)”.
>
>
>
>
>
> --
> View this message in context:
>
http://drools.46999.n3.nabble.com/How-to-use-Drools-s-global-object-in-a-...
> Sent from the Drools: User forum mailing list archive at
Nabble.com.
>
> _______________________________________________
> rules-users mailing list
> rules-users(a)lists.jboss.org
>
https://lists.jboss.org/mailman/listinfo/rules-users
>