How to convert a string to an existing object in Groovy?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to convert a string to an existing object in Groovy?



How to call its methods if I only know the literal name of the existing object?



For example:


class Cat
def bark()
println "I am a cat."



class Dog
def bark()
println "I am a dog."



def cat = new Cat()
def dog = new Dog()

def animal = 'cat'
"$animal".bark() // Error



As below, I only know the name of the animal (maybe cat or dog). How do I use this object?




2 Answers
2



if the cat and dog are defined as fields, you can use this:


cat


dog


this


this."$animal".bark()



or


this[ animal ].bark()


def animals = [
cat: new Cat(),
dog: new Dog(),
]

def name = 'cat'
animals[name].bark()






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard