Search code examples
mvel

How to access a variable declared inside a MVEL expression?


Suppose I write a code like this:

public class SomeClass() {
  public static void main(String[] args) {
     MVEL.eval("boolean boolVar = 2<3;");
  }
}

Now is it possible to access this boolVar variable in the Java code anywhere. Example: Can I print the value of boolVar using

System.out.print(boolVar);

in the main method just below the MVEL line.


Solution

  • Remember doing as above, boolean boolVar becomes local variable, and MVEL cannot compile it also.

    1.) Need to pass class object.

    2.) Create boolean property in class, and assign to it.

    Expression to be evaluated : MVEL.eval("obj.output = 2<3;", map);

    Please try below code :-

    import java.util.HashMap;
    import java.util.Map;
    
    import org.mvel2.MVEL;
    
    public class SomeClass {
    
        private boolean output;
    
        public boolean isOutput() {
            return output;
        }
    
        public void setOutput(boolean output) {
            this.output = output;
        }
    
        public static void main(String[] args) {
            SomeClass myObj = new SomeClass();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("obj", myObj);
    
            MVEL.eval("obj.output = 2<3;", map);
            System.out.println(myObj.isOutput());
    
            MVEL.eval("obj.output = 2>3;", map);
            System.out.println(myObj.isOutput());
    
        }
    }
    

    output

    true
    false