Search code examples
javadrools

Accessing Child class properties from parent class in drools


I have a parent class Vehicle() passed in drools xls file how can I access the properties of the child class Car()?

I've tried casting it but it drools doesn't recognize the method cast

(Car.cast(vehicle)).isManual()

Edit by laune from OP's comment: The drools version I'm using is 4.0.7

import workspace.sampleproj.domain.* 
function boolean checkIfCarManual(Vehicle vehicle){
    if (vehicle.isCar() == true){ 
        if((Car.cast(vehicle).isManual() == true){ 
            return true;
        } else {
            return false; 
        }
    } else {
        return false;
    }
 }

Solution

  • Drools cannot recognize what cannot be recognized.

    If your class Car has a static method cast(Vehicle v), it should be recognized. (If there is no such method, you'll get an error.)

    class Car extends Vehicle {
        public static Car cast( Vehicle v ){ return (Car)v; }
        ...
    }
    

    Perhaps you tried to use the cast method of java.lang.Class? If so, you'll have to write

    (Car.class.cast(vehicle)).isManual()
    

    Later And there's no reason why you shouldn't be able to use a straightforward cast:

    function boolean checkIfCarManual(Vehicle vehicle){
        return vehicle.isCar() && ((Car)vehicle).isManual();
    }