amirse
4 years agoContributor
Replace one part in a request with the value from an variable
Hi, Is there a way to replace the "XXXX" in the method below with the value of the variable replaceToken? def replaceToken = "username" parsedJson.secrets.XXXX.toString() I.e., I would l...
- 4 years ago
Hi,
Have a look at http://blog.gtiwari333.com/2012/08/groovy-grails-dynamic-method-n-variable.html
You can call methods using variables and array elements.
I've created a small Groovy script as a demo. See below.
def myObj = new MyClass(); // Call in the usual way. log.info("Call in the usual way."); log.info(myObj.methodOne()); log.info(myObj.methodTwo()); log.info(myObj.methodThree()); log.info("-------------------------------------------"); // Call using a variable. log.info("Call using a variable"); def methodToCall = "methodOne"; log.info(myObj."$methodToCall"()); methodToCall = "methodTwo"; log.info(myObj."$methodToCall"()); methodToCall = "methodThree"; log.info(myObj."$methodToCall"()); log.info("-------------------------------------------"); log.info("Call with method name in an array"); def myArray = ["methodOne", "methodTwo", "methodThree"]; log.info(myObj.(myArray[0])()); log.info(myObj.(myArray[1])()); log.info(myObj.(myArray[2])()); log.info("-------------------------------------------"); class MyClass { MyClass(){ // empty constructor } def methodOne(){ return "I am method one"; } def methodTwo(){ return "I am method two"; } def methodThree(){ return "I am method three"; } }