groovy中的变量如何通过变量类型设置条件

du7egjpx  于 2022-11-01  发布在  其他
关注(0)|答案(2)|浏览(174)

我是一个新手,我正在寻找一些建议。如何在Groovy中创建一个条件,以便如果变量是字符串,则执行一个操作,如果表是另一个,并且正如所需的那样,如果变量等于零,则不传输任何内容

//aditionalArgs= "test1 = add1 , tets2= add2 "
aditionalArgs = ["test1=arg1", "test2=arg2"]
println(aditionalArgs.class)

def args = ""

if ((aditionalArgs != "class java.lang.String" ) || (aditionalArgs > 0)){
 def list = aditionalArgs.replace("--build-arg", "").split(',')
  list.each { val->
      args += " --build-arg $val"
  }

  println(args.replace("",""))
}

if (aditionalArgs == "ArrayList" ){
 def list = aditionalArgs("--build-arg", "").split('[' , ']')
 list.each { val-> 
     args += " --build-arg $val"
}

  println(args.replace("",""))
}

else(aditionalArgs.length() > 0){
  println "empty aditionalArgs"
}```
llycmphe

llycmphe1#

if (aditionalArgs instanceof String && aditionalArgs.length() > 0) {
    ...
} else if (aditionalArgs instanceof List && aditionalArgs.size() > 0) {
    ...
} else {
    println "unsupported arg type '${aditionalArgs?.getClass()}' or value '${aditionalArgs}'"
}
kxe2p93d

kxe2p93d2#

您的代码建议您更希望使用switch操作:

switch( aditionalArgs ){

  case String:
    // do stuff with String
    break

  case List:
    // do stuff with (Array)List 
    break

  case Number:
    // do something with Number
    break

  default:
    throw new Exception( 'I have no idea' )
}

更多关于声明的内容是in the docs

相关问题