Wednesday 30 January 2019

Groovy: List all the properties of a class


Using meta field ‘properties’ of an instance, you can list all the properties of a class.

HelloWorld.groovy
class Employee {
 String name
 int id
}

Employee emp1 = new Employee()
employeeProperties = emp1.properties.keySet();

println "Properties of the class Employee are : "
for(prop in employeeProperties){
 println "$prop"
}

Output
Properties of the class Employee are :
class
id
name

Let’s add one field ‘organization’ (Filed is not a property) and confirm that it is not part of employee properties.


HelloWorld.groovy
class Employee {
 String name
 int id
 
 public String organization
}

Employee emp1 = new Employee()
employeeProperties = emp1.properties.keySet();

println "Properties of the class Employee are : "
for(prop in employeeProperties){
 println "$prop"
}

Output
Properties of the class Employee are :
class
id
name



Previous                                                 Next                                                 Home

No comments:

Post a Comment