Search code examples
grailsgrails-orm

How do you call a constructor from using getArtefact in Grails 3


I need a list of my domains, and I am getting them by using:

def domains = grailsApplication.getArtefacts("Domain")*.clazz

In each of my domains is a constructor, I want to do something like this:

def item = new domains[0](object)
item.save()

essentially making a generic save.


Solution

  • I figured out a way to invoke the constructor. I don't know if it is the best way to do it. Example code below:

    //provides all Domain classes in your project in an ArrayList
    //You can also use getArtefact("Domain", "classname")*.clazz to return a subset
    
    def domains = grailsApplication.getArtefacts("Domain")*.clazz
    
    def domain = domains[0].newInstance(object) //Whatever your constructor wants variable: "item" works as well
    def domain.save()
    

    Got this working thanks to http://mrhaki.blogspot.ca/2010/06/groovy-goodness-create-class-instance.html