gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:29:49 35 4
gpt4 key购买 nike

我想将转换添加到类 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

我得到异常(exception)
java.lang.IllegalArgumentException: argument type mismatch

问题是什么? clsClass类型。

最佳答案

你很接近...

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

关于groovy - 从字符串到某个对象的自定义类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39616018/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com