Wednesday, May 06, 2009

When Class.forName() Can't Find The Domain Class

I was trying to use reflection to create a domain class:

try {
def clazz = Class.forName(domainClassName)
def obj = clazz.newInstance()
}
catch (ClassNotFoundException ex) {
...
}


To my surprise, I caught ClassNotFoundException at line 2. After searching for a while, I found an explanation in this thread. Burt Beckwith explained that classes loaded without a ClassLoader will not resolve dynamically added classes such as the domain classes. He suggested to use the other variant:

try {
def clazz = Class.forName(domainClassName, true, Thread.currentThread().contextClassLoader)
obj = clazz.newInstance()
}
catch (ClassNotFoundException ex) {
...
}

Thanks for the tips, Burt.

No comments: