从字符串到某个对象的自定义类型转换

lap*_*ots 4 groovy

我想为Stringtype 的对象添加到类的转换Example

当我喜欢这个的时候

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
Run Code Online (Sandbox Code Playgroud)

我得到例外

java.lang.IllegalArgumentException: argument type mismatch
Run Code Online (Sandbox Code Playgroud)

问题是什么?clsClass类型。

Ren*_*ato 6

你很接近...

请注意,该asType方法由 Groovy 的 String 扩展类实现,称为StringGroovyMethods

所以有效的代码是这样的:

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
Run Code Online (Sandbox Code Playgroud)

哪个打印:

5
Example(10)
Run Code Online (Sandbox Code Playgroud)