简体   繁体   中英

How to add element to array with Drools (mvel)

I need insert a new value in a exist array with Drools. My example:

rule "insert new address"
dialect "java"
when
     $data : Data( source.address != null)
then
     Address address = (Address) $data.source.address
     System.out.println("Element: "+address );
     $data.target.addressList.add(address);
end

The error that happend is this: Exception executing consequence for rule "insert new address" in rules: [Error: $data.target.addressList.add(address): null]

EDIT : Added the model

public class Data {
  private Source source;
  private Client target;
}

public class Source {
  ...
  private Address address;
}

public class Client {
  ...
  private List<Address> addressList;
}

In answer to the question in your title, which is how to add an element to array -- the answer is basically "the same way you would in Java."

To answer the question you actually asked, which has no arrays, your error is effectively a NullPointerException, or another indicator that the field cannot be modified (eg an immutable list.)

This:

Error: $data.target.addressList.add(address): null]

Means that either $data.target or $data.target.addressList is null, or possibly $data.target.addressList is an immutable list.

Make sure that whatever "target" is has been initialized, and that its "addressList" is also initialized as a mutable list type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM