简体   繁体   中英

Groovy / Grails - How to get class instance from String?

I'm trying to derive the class instance of a groovy class from the name of string.

For example, I'd like to do some code along these lines:

def domainName

domainName = "Patient"

// but following line doesn't work, domainName is a String
def domainInstance = domainName.get(1);  

The Grails way would be to use GrailsApplication#getArtefact . eg,

def domainInstance = grailsApplication.getArtefact("Domain",domainName)?.
        getClazz()?.get(1)

The advantage of doing it this way as opposed to Class.forName is that if there is no domain class with that name, getArtefact just returns null instead of throwing an exception.

这将有效:

   Class.forName("Patient",  false, Thread.currentThread().contextClassLoader).get(1)

Well,

  1. Try to implement your code using packages

  2. Try this code: I don't know if it will work ok?

def domainInstance = Class.forName("Patient").newInstance()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM