有没有办法在使用GroovyShell.evaluate时跳过MissingPropertyException?
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
shell.evaluate("a=5; b=1") // works fine
// How to not get MissingPropertyException, or silently ignore property 'a'
shell.evaluate("a; b=1") // MissingPropertyException for 'a'我知道Expando解决方案,有没有一种不定义类的方法?
发布于 2021-11-03 17:49:30
一种非常简单的方法是覆盖Binding.getVariable。请注意,这非常简单:“所有异常”都被忽略--您可能希望有更好的日志记录或更准确的错误处理。
import groovy.lang.*
class NoOpBinding extends Binding {
@Override
Object getVariable(String name) {
try {
return super.getVariable(name)
}
catch (Throwable t) {
println "Ignoring variable=`$name`"
return null
}
}
}
def shell = new GroovyShell(new NoOpBinding())
shell.evaluate("a; b=1") // MissingPropertyException for 'a'
// → Ignoring variable=`a`
println shell.getVariable('b')
// → 1发布于 2021-11-04 00:02:50
你可以这样做:
def binding = [:].withDefault { }
def shell = new GroovyShell(binding as Binding)
shell.evaluate 'a; b=1'https://stackoverflow.com/questions/69828430
复制相似问题