Recently on a project, I was creating a number of command objects to accept incoming parameters from a POST call from an iPhone with which I needed to sync data. I created a parent class for all command object classes to accept the common properties and created individual command object classes to accept any additional parameters.
The use case was that the name of the command object class was being created dynamically from the URL. Now, when I was trying to create a new instance of a command object in a controller using the following code, I got a ClassNotFoundException to my utter surprise:
DefaultGrailsApplication grailsApplication = ApplicationHolder.application.mainContext.getBean("grailsApplication")
def clazz = grailsApplication.getClassForName("com.intelligrape.co.sync.SyncCO").newInstance()
So I tried going through the Java style of fetching a class instance as follows:
def clazz = Class.forName("com.intelligrape.co.sync.SyncCO").newInstance()
Needless to say, I ran into the same problem again. After a lot of searching on the Internet and headbanging, I realized that classes in the src/groovy or src/java are not available to the grails class loader and they are loaded by the URLClassLoader which is a subclass of Java’s ClassLoader. Along with Uday’s help and a nabble post, I realized that I needed to use the three parameter Class.forName() method to create a new instance of a POGO or a POJO.
I ended up using the following syntax which worked for me in this case:
def clazz = Class.forName("com.intelligrape.co.sync.SyncCO", true, Thread.currentThread().getContextClassLoader()).newInstance()
The above code gets a reference of the current executing thread’s root class loader to fetch an instance of all classes loaded in the current executing application. Documentation for the method is located here: Class.forName()
I hope this helps any lost soul who has tried and failed at creating a new instance of a POGO.