Dynamically Accessing Objects

We’ve looked at ways to query for methods and properties, and at ways to invoke them dynamically. There are other convenient ways to access properties and call methods in Groovy. We will look at them now using an instance of String as an example. Suppose we get the names of properties and methods as input at runtime and want to access these dynamically. Here are some ways to do that:

ExploringMOP/AccessingObject.groovy
 
def​ printInfo(obj) {
 
// Assume user entered these values from standard input
 
usrRequestedProperty = ​'bytes'
 
usrRequestedMethod = ​'toUpperCase'
 
 
println obj[usrRequestedProperty]
 
//or
 
println obj.​"​$usrRequestedProperty​"
 
 
println obj.​"​$usrRequestedMethod​"​()
 
//or ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.