Grails Class.forName ClassNotFoundException

Hi everybody. While I am writing introduction post about grails, I would like to share solution for a problem I have encountered today.

Lets say inside Grails application you want to get a Class object for some Groovy/Java class, which is located in src/groovy or src/java folders by class name. For example, in BootStrap.groovy. You might end up with code like this:

// Somewhere in BootStrap.groovy
def obj = Class.forName("com.binarybuffer.grails.MyCoolClass")

You may find that this code throws ClassNotFoundException. You might think that class is not included in classpath, but you can create instance of that class easily:

import com.binarybuffer.grails.MyCoolClass
// Somewhere in BootStrap.groovy
def temp = new MyCoolClass()  // No exception, object is created!
def obj = Class.forName("com.binarybuffer.grails.MyCoolClass")

This happens because by default Class.forName() method uses this.getClass().getClassLoader() class loader, but to have proper access to all your grails classes (not grails artifacts) you should explicitly specify Thread class loader like this:

Class.forName(
    "com.binarybuffer.grails.MyCoolClass",
     true,
     Thread.currentThread().contextClassLoader)

Thats it! No exception is thrown and you are get your class. And to acces grails artifacts (controller, services classes) you should use grailsApplication.getClassForName() method.