- Notifications
You must be signed in to change notification settings - Fork 0
8) Accessing Properties and Methods of Objects
pranithcodes edited this page Apr 6, 2018 · 1 revision
In this session we will develop JEXL expressions that will allow us to access properties variable and methods which are both private and public.
For this we shall create a simple Employee class class Employee { private String name; Integer salary;
public Employee(String name, Integer salary) { this.name = name; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getLengthOfName() { return name.length(); } }
Accessing Variables:
Using JEXl expression, we can access both public and private variable of a object using Dot(.) opertor. If employee is the name of the object in the context then we can use employee.name to access the varibles.
Similarly, we can assign value to the properties using below syntax.
employee.name = “Iron Man” public class UsingClasses {
public static void main(String[] args) { JexlEngine jexl = new JexlBuilder().create(); JexlContext context = new MapContext(); Employee employee = new Employee("Falcon", 100000); context.set("employee", employee); context.set("out", System.out); JexlExpression e = jexl.createExpression("out.println(\" EMPLOYEE NAME ::\" + employee.name)"); e.evaluate(context); e = jexl.createExpression("out.println(\" EMPLOYEE SALARY ::\" + employee.salary)"); e.evaluate(context); e = jexl.createExpression("employee.name = \" Iron Man \""); e.evaluate(context); e = jexl.createExpression("out.println(\" EMPLOYEE NAME ::\" + employee.name)"); e.evaluate(context); } } Output:
EMPLOYEE NAME ::Falcon EMPLOYEE SALARY ::100000 EMPLOYEE NAME :: Iron Man
**Accessing Methods: **
JEXL allows you to access any methods of a Java Object using (.) Operator.
public static void main(String[] args) { JexlEngine jexl = new JexlBuilder().create(); JexlContext context = new MapContext(); Employee employee = new Employee("Falcon", 100000); context.set("employee", employee); context.set("out", System.out); JexlExpression e = jexl.createExpression("out.println(\" Length of EMPLOYEE NAME ::\" + employee.getLengthOfName())"); e.evaluate(context); }