Groovy : What is Direct field access operator and how to use it

Direct field access operator

In groovy when we access the property of any object as object.property then groovy under the hood calls the getter method of the property even if we have not specified it. The default getter and setter methods return the property and set the property respectively.
Let's have a look at the example.
class User {  
  String name
  String email
  
  String getName(){
    return "Name is $name"
  }
  
}

User u = new User(name : 'ekiras' , email : 'ekansh@ekiras.com')

println u.name
When you execute the above code you will get the output Name is ekiras.
Note
What happens under the hood is u.name will internally call the getter method of instance variable name.
Here calling u.getName()' is equivalent to calling u.name

Also, all the classes and their instance variables are by default public in nature. So you can access the instance variable without calling the getter method byb using the Direct Field Access Operator
Syntax of Direct Field Access operator is as below
<object>.@<property>
So we can use this operator as shown below
class User {  
  String name
  String email
  
  String getName(){
    return "Name is $name"
  }
  
}

User u = new User(name : 'ekiras' , email : 'ekansh@ekiras.com')
println u.name  // 1
println u.@name  // 2
The above code will give the following output
Output

Name is ekiras
ekiras

The 1st print statement prints Name is ekiras because it calls the getter method of the property name while 2nd statement calls the property directly.

No comments :

Post a Comment