I know in Groovy you can invoke a method on a class/object using a string. For example:
Foo.'get'(1) /* or */ String meth = 'get' Foo.'$meth'(1)
Is there a way to do this with the class? I have the name of the class as a string and would like to be able to dynamically invoke that class. For example, looking to do something like:
String clazz = 'Foo' '$clazz'.get(1)
I think I’m missing something really obvious, just am not able to figure it out.
Try this:
A little bit longer but should work.
If you want to create ‘switch’-like code for static methods, I suggest to instantiate the classes (even if they have only static methods) and save the instances in a map. You can then use
to select one of them.
[EDIT]
'$name'is aGStringand as such a valid statement.'$name'.foo()means ‘call the methodfoo()of the classGString.[EDIT2] When using a web container (like Grails), you have to specify the classloader. There are two options:
or
The first option will work only in a web context, the second approach also works for unit tests. It depends on the fact that you can usually use the same classloader as the class which invokes
forName().If you have problems, then use the first option and set the
contextClassLoaderin your unit test: