简体   繁体   English

揭秘如何设定价值

[英]Mvel how to set value

I need to set value of an attribute if MVel expression is true. 如果MVel表达式为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);

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 所以在这里我实际上是将值赋给MyMaths类的变量“ a

Output - 20 输出-20

Now change the value from 'Ankur' to 'XYZ', output will be 25. 现在将值从“ Ankur”更改为“ XYZ”,输出将为25。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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