Why doesn't Class.forName work on grails domai

2019-04-16 02:54发布

问题:

I know that using Class.forName to load a grails domain class does not work, but I'm not sure why that is. I'm guessing there is some sort of grails magic happening but it would be nice to understand what it is.

I ended up using

GrailsDomainClass dc = grailsApplication.getDomainClass('mypack.myclass' )
def newDomainObject = dc.clazz.newInstance()

But I'm not sure why just doing Class.forName('mypack.myclass') doesn't work.

回答1:

Grails uses custom classloaders, so you need to use the 3-arg variant with the classloader that Grails uses and registers as the context classloader:

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