在groovy中输入cast变量取决于另一个变量类?

Yas*_*wal 2 groovy

例如

def a = "567"
def b = 0
Run Code Online (Sandbox Code Playgroud)

现在我想检查'a'是否可以转换为int(因为b的类是int)?

我可以

def x =  a as int
Run Code Online (Sandbox Code Playgroud)

但是做

def x = a as b.getClass()
Run Code Online (Sandbox Code Playgroud)

给出错误.

我怎样才能做到这一点?

tim*_*tes 5

说你有:

def a = '567'
def type = Integer
Run Code Online (Sandbox Code Playgroud)

你可以asType:

assert a.asType( type ) == 567
Run Code Online (Sandbox Code Playgroud)

或者如果你想使用其他变量的类型;

def a = '567'
def b = 0

assert a.asType( b.getClass() ) == 567
Run Code Online (Sandbox Code Playgroud)