Miguel Pardal Miguel Pardal - 1 year ago 124
Groovy Question

Groovy way to dynamically instantiate a class from String

The answers of this question about the Groovy way to dynamically invoke a static method were very helpful but I'm having trouble with the following case:

I defined a simple Groovy class:

class Item {
def id = 1
def data = [ "a", "b" ]

I then defined a simple utility class that wants to dynamically load the Item class:

class Util {
static def main(args) {
def cls = "Item" as Class
def instance = cls.newInstance()
println instance.toString()

Util.groovy is in the same folder as Item.groovy

When I try to run Util.groovy I get the following error:

Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object 'Item' with class 'java.lang.String'
to class 'java.lang.Class' due to:
java.lang.ClassNotFoundException: Item
at Util.main(Util.groovy:3)

The only way that I could make it work was by using groovyc to precompile Item.groovy, but this misses the point of being Groovy :)

Answer Source

This works, using the underlying GroovyClassLoader:

def instance = this.class.classLoader.loadClass( 'Item', true, false )?.newInstance()