Problem
You have a domain class hierarchy and want to use the classes in an association. You typically use the base class in a hasMany:
class Domain { static hasMany = [others:BaseClass] }
Dependent on the actual class in the set others
you want to call a different method:
public doSomething(domain) { domain.others.each {doThis(it)} } public doThis(ChildClassOne c) {} public doThis(ChildClassTwo c) {} ...
Here the proxy mechanism of Hibernate (and Grails) causes a MethodMissingException to be thrown because the proxies are instances of the base class and not the actual child ones.
One way would be to activate eager fetching or you could use…
Solution: A dynamic visitor
Declare a visit method in the base class which takes a closure
def visit(Closure c) { return c(this) }
and make the dispatch in a method for the base class:
public doThis(BaseClass c) { return c.visit {doThis(it)} }