Skip to content

defining facts

夏天松 edited this page Sep 19, 2017 · 10 revisions

The Facts API is an abstraction of the set of facts on which rules should be checked. Internally, Facts holds a HashMap<String, Object>, this means that:

  • Facts are named and should have a unique name but not null
  • Any Java object can act as a fact

Here is an example of how to define facts:

Facts facts = new Facts();
facts.add("rain", true);

Facts can be injected in rules condition and action methods using the @Fact annotation. In the following rule, the rain fact is injected in the rain parameter of the itRains method:

@Rule
class WeatherRule {

    @Condition
    public boolean itRains(@Fact("rain") boolean rain) {
        return rain;
    }

    @Action
    public void takeAnUmbrella(Facts facts) {
        System.out.println("It rains, take an umbrella!");
        // can add/remove/modify facts
    }

}

Parameters of type Facts will get injected all known facts (like in the takeAnUmbrella action method).

If an injected fact is missing, the engine will throw a RuntimeException.

Clone this wiki locally