Groovy supports two ways to access the fields of a class.
a.
Using . operator
b.
Using subscript [] operator
Example
Employee emp1 = new Employee()
emp1.name = "Krishna"
emp1.id = 523
You can access the property using subscript operator.
emp1["name"] = "Yada"
emp1["id"] = 567
Employee emp1 = new Employee()
emp1.name = "Krishna"
emp1.id = 523
You can even access the fields of an object using
subscript operator like below.
emp1["name"] = "Yada"
emp1["id"] = 567
HelloWorld.groovy
class Employee{ String name int id } void printEmployee(emp){ println "name : ${emp.name}" println "id : ${emp.id}" } Employee emp1 = new Employee() emp1.name = "Krishna" emp1.id = 523 printEmployee(emp1) emp1["name"] = "Yada" emp1["id"] = 567 printEmployee(emp1)
Output
name : Krishna
id : 523
name : Yada
id : 567
No comments:
Post a Comment