Question

I have a compiled grails project, and from a separate groovy project, I reflectively load a domain class as follows

Class clazz = Class.forName('mypack.myclass', true, Thread.currentThread().contextClassLoader)
def newDomainObject = clazz.newInstance()

When running from outisde of grails (in my separate groovy project), the object is not recognized as a GroovyObject.

println newDomainObject instanceof GroovyObject // false

Since I'm running from outside of grails, I would think that groovy would treat the domain class just like any other class (and from looking at the class file, it does implement GroovyObject).

My best guess is that it has something to do with how grails compiles the domain object, but I'm not sure what's going on here.

Note this is related to Why doesn't Class.forName work on grails domain classes, but not the same.

Was it helpful?

Solution

This seems impossible - just like javac changing classes that don't explicitly extend a base class to extend java.lang.Object, groovyc changes all Groovy classes to implement groovy.lang.GroovyObject.

Are you looking at a class compiled in the Groovy project from a shared .groovy class, or a compiled class in a jar?

instanceof is tricky though due to Groovy's order of evaluation; try adding parens:

println (newDomainObject instanceof GroovyObject)

If that still prints false, try recursively dumping all of the implemented interfaces:

while (clazz != Object) {
   def interfaces = clazz.interfaces
   if (interfaces) {
      clazz.interfaces.each { println "$clazz.name implements $it.name" }
   }
   else {
      println "$clazz.name doesn't directly implement any interfaces"
   }
   clazz = clazz.superclass
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top