Grails: Dynamically create instance of a POGO class
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:
[code]
DefaultGrailsApplication grailsApplication = ApplicationHolder.application.mainContext.getBean("grailsApplication")
def clazz = grailsApplication.getClassForName("com.intelligrape.co.sync.SyncCO").newInstance()
[/code]
So I tried going through the Java style of fetching a class instance as follows:
[code]
def clazz = Class.forName("com.intelligrape.co.sync.SyncCO").newInstance()
[/code]
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:
[code]
def clazz = Class.forName("com.intelligrape.co.sync.SyncCO", true, Thread.currentThread().getContextClassLoader()).newInstance()
[/code]
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.
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
Thank, solved my headache
i like to disagree with people just for fun but your style makes that hard
@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.
I am curious. Why not just do a new SyncCO()?