user1432980 user1432980 - 2 months ago 22
Groovy Question

custom type conversion from string to some object

I want to add conversion to class

String
for object with type
Example
.

When I do like this

class Example {
def x = 5
}

class ExampleConversionCategory {
static def support = String.&asType
static Object asType(String self, Class cls) {
if (cls == Example.class) {
"convert"
} else { support(cls) } // argument type mismatch
}
}

String.mixin(ExampleConversionCategory)

def x = "5" as int
println x


I get exception

java.lang.IllegalArgumentException: argument type mismatch


What is the problem?
cls
has
Class
type.

Answer

You were pretty close...

Notice that the asType method is implemented by the Groovy's String extension class, called StringGroovyMethods.

So the code that works is this one:

import groovy.transform.Canonical
import org.codehaus.groovy.runtime.StringGroovyMethods

@Canonical
class Example {
    def x = 5
}

class ExampleConversionCategory {
    static final def convert = StringGroovyMethods.&asType

    static def asType( String self, Class cls ) {
        if ( cls == Example ) new Example( x: 10 )
        else convert( self, cls )
    }
}

String.mixin( ExampleConversionCategory )

println "5" as int
println 'A' as Example

Which prints:

5
Example(10)