Skip to content

Context Object

tporcham edited this page Jan 30, 2019 · 1 revision

A context object in MVEL is an optional enviromental element that can be used in conjunction with, or an alternative to, injected variables into the parser/interpreter.

For example:

String test = "Hello";
Object result = MVEL.eval("toUpperCase()", test);

In this example, we're using the test String object as our context object, allowing us to execute the toUpperCase() method as a local function in our expression. We can also access other methods in the java.util.String class as bean properties.

Consider:

public class User {
        private String name;
        private String password;
        private int age;


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }

Now, just for example purposes, lets apply this class in one of our tests:

User user = new User();
user.setName("Bob");
user.setPassword("Despot");
user.setAge(30);

String name = (String) MVEL.eval("name", user);

In this example, the value of the variable name returned by the expression will be "Bob".

Priority of Resolution

In situations where both external variables and a context object are being used, the MVEL runtime will look for a variable first, and then look to see if the context object contains the identifier.