Mikey
Mikey

Reputation: 4742

Grails automatically coerce strings into one of my domain classes

I have a domain class like:

class MyDomainClass{
  String name
}

And an interface with a signature like:

BigDecimal doBigThangs(MyDomainClass startHere)

I want to be able to call it like this

doBigThangs('stuff')

And have it automatically coerse the string 'stuff' into the appropriate MyDomainClass. This is what I have tried, but perhaps I need to use "asType" or something.

ExpandoMetaClass.enableGlobally()
String.metaClass.toMyDomainClass = {->MyDomainClass.findByNameLike(delegate)}

Upvotes: 0

Views: 137

Answers (1)

ataylor
ataylor

Reputation: 66069

You are correct: you can add a type conversion by overriding asType. Your example would look something like this:

oldAsType = String.metaClass.getMetaMethod("asType", [Class] as Class[])
String.metaClass.asType = { Class c ->
    if (c == MyDomainClass) { 
        MyDomainClass.findByNameLike(delegate)
    } else {
        oldAsType.invoke(delegate, c)
    }
}

However, groovy won't silently cast a String to another type on a method call. You'll have to call your method like this:

doBigThangs('stuff' as MyDomainClass)

Upvotes: 1

Related Questions