July 2013
Intermediate to advanced
370 pages
8h 27m
English
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"() ... |
Read now
Unlock full access