Reputation: 36713
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);
Upvotes: 11
Views: 7494
Reputation: 4404
Well,
Try to implement your code using packages
Try this code: I don't know if it will work ok?
def domainInstance = Class.forName("Patient").newInstance()
Upvotes: -3
Reputation: 4789
This will work:
Class.forName("Patient", false, Thread.currentThread().contextClassLoader).get(1)
Upvotes: 2
Reputation: 21519
The Grails way would be to use GrailsApplication#getArtefact. e.g.,
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.
Upvotes: 23