0

I need to set value of an attribute if MVel expression is true. Can any one please help me, how to do that.

Example code as below:

      LineItem lineItem = new LineItem();

      Address address = new Address();
        address.setAddress1("ABC");
        address.setAddress2("PA");

      lineItem.setShipFromAddress(address);

    ParserContext parserContext = ParserContext.create();
    parserContext.stronglyTyped().withInput("lineItem",LineItem.class)
          .withInput("shipFromAddress", Address.class);

        Object compiledWithSet = MVEL.compileExpression("( shipFromAddress.address1 contains 'ABC' || shipFromAddress.address1 contains 'ABC DEF' ) && (shipFromAddress.address2 contains 'PA') ? setShipFromLocation('PA1') : ",parserContext);
        MVEL.executeExpression(compiledWithSet, lineItem);
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116

1 Answers1

0

There is a solution to your problem, but can you elaborate more on your use case. Here is the small sample answer, hope this might help you out to get started.

public class MyMaths {

    int a;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }
}

public static void main(String[] args) {

        Map map = new HashMap();
        MyMaths mayMaths = new MyMaths();
        map.put("obj", mayMaths);
        map.put("name", "Ankur");

        String expression1 = "obj.a = ( name == 'Ankur') ? 20 : 25";

        Serializable compiled1 = MVEL.compileExpression(expression1);

        MVEL.executeExpression(compiled1, map);

        System.out.println(mayMaths.getA());

    }

So here i am actually assigning the value to variable "a" of class MyMaths

Output - 20

Now change the value from 'Ankur' to 'XYZ', output will be 25.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116