问题
I'm working with a system where some of the data inserted into a Drools engine follows this (heavily oversimplified) format:
public class Item {
public String getValueType() { ... }
public Object getValue() { ... }
}
The values may be several different types. Now, I want to create a bunch of Drools rules to check various fields of the values, something along the lines of:
$a : Item(valueType == "Car", value.owner.location == "At Home")
$b : Item(valueType == "Payments", value.rates.discounts.percent == 1337)
$c : Item(valueType == "Royalty", value.student.occupation == "Librarian")
...and so on. Now, the problem I'm facing is that Drools statically type checks the rules as they're loaded, disallowing this use as Object isn't guaranteed to have the owner/rates/student fields and so on.
Is there a way to do this, possibly some kind of typecasting or bypassing the type checking?
(Note: Unfortunately, it is as of right now not an option to change the model to be typed instead of shoving everything into Objects.)
回答1:
Starting from Drools 5.5.0 you can 'cast' the attributes of your facts. Please read section 4.1.1.2 of this document: http://docs.jboss.org/drools/release/5.5.0.Final/droolsjbpm-introduction-docs/html_single/
Basically, what you need to do is:
$a : Item(valueType == "Car", value#Car.owner.location == "At Home")
Disclaimer: I never tried this before.
回答2:
you can also use @typesafe(false) on a type declaration, but casting as shown in the other answer is much better.
来源:https://stackoverflow.com/questions/14853310/type-unsafe-object-field-access-in-drools