Close

Groovy Operators - Direct Field Access Operator

[Updated: Dec 5, 2018, Created: Dec 5, 2018]

Groovy supports shorthand syntax for invoking getter and setter.

Quick example

public class Person{
  String name;

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

  public String getName(){
    return name;
  }
}

Calling getter/setter:

def e = new Person();
//calling getter setters
e.name = "Jackie" //will call setter
println e.name //will call getter

//accessing field directly
e.@name = "Jackie" // will set field directly
println e.@name //will read field directly

As seen above use of .@ forces usage of the field directly instead of calling getter or setter.

Example

groovy-direct-field-access-operator/src/Employee.java

public class Employee {
  String name;
  String dept;

  public String getName() {
      printCurrentMethodName();
      return name;
  }

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

  public String getDept() {
      printCurrentMethodName();
      return dept;
  }

  public void setDept(String dept) {
      printCurrentMethodName();
      this.dept = dept;
  }

  private void printCurrentMethodName() {
      //using java 9 stack walker to get current method name
      String methodName = StackWalker.getInstance()
                                     .walk(s -> s.skip(1).findFirst())
                                     .get()
                                     .getMethodName();
      System.out.println("method called: " + methodName);
  }
}

Using shorthand syntax of getter/setter

def employee = new Employee();
//calling setters
employee.name = "Mike"
employee.dept = "IT"
//calling getters
println employee.name
println employee.dept



Output

method called: setName
method called: setDept
method called: getName
Mike
method called: getDept
IT

Reading/writing fields directly

def employee = new Employee();
//setting fields directly
employee.@name = "Mike"
employee.@dept = "IT"
//reading fields directly
println employee.@name
println employee.@dept

Output

Mike
IT

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 11
Direct Field Access Operator Select All Download
  • groovy-direct-field-access-operator
    • src
      • DirectFieldAccessOptExample.groovy

    See Also