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

时间:2016-09-21 12:01:06

标签: groovy

我想为类型为String的对象添加转化为类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

我得到例外

java.lang.IllegalArgumentException: argument type mismatch

有什么问题? clsClass类型。

1 个答案:

答案 0 :(得分:4)

你非常接近......

请注意,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

打印哪些:

5
Example(10)