Grails: Dynamically create instance of a POGO class

15 / Jun / 2011 by Roni C. Thomas 5 comments

Hi guys,

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("").newInstance()

So I tried going through the Java style of fetching a class instance as follows:

def clazz = Class.forName("").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("", 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.


comments (5)

  1. kiran

    Hi Grails,
    i have a doubt
    following is my code

    1. String className= “com.Simple”;
    2. Class forName = Class.forName(className);
    3. Object newInstance = forName.newInstance();

    in the above code, className is dynamic. in 3rd line how to cast the objce into my classname

  2. roni

    @antoine the use case was somewhat different. Actually SyncCO was an abstract class and I had to dynamically create the class name of the actual CO whose new instance had to created. The above example was simply to illustrate the point that POGO instances cannot be created as simply as domain classes.


Leave a Reply

Your email address will not be published. Required fields are marked *