Java 如何确定脚本引擎中运行的 Groovy 代码中是否存在变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42465028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I determine if a variable exists from within the Groovy code running in the Scripting Engine?
提问by ycomp
How can I determine if a variable exists from within the Groovy code running in the Scripting Engine?
如何确定脚本引擎中运行的 Groovy 代码中是否存在变量?
The variable was put by ScriptEngine's put method
采纳答案by Aliaksandr Pyrkh
In the groovy.lang.Scriptthere is a method public Binding getBinding(). See also groovy.lang.Bindingwith method public boolean hasVariable(String name).
在groovy.lang.Script 中有一个方法public Binding getBinding()。另见groovy.lang.Bindingwith method public boolean hasVariable(String name)。
Thus you can simple check variable existence like
因此,您可以简单地检查变量是否存在,例如
if (binding.hasVariable('superVariable')) {
// your code here
}
回答by Valdi_Bo
Variables injected by the Scripting Engine are held within
binding.variables, so you can e.g. check for variable named xx:
脚本引擎注入的变量保存在 中
binding.variables,因此您可以例如检查名为 的变量xx:
if (binding.variables["xx"]) ...
回答by Maximilian Mordig
// Example usage: defaultIfInexistent({myVar}, "default")
def defaultIfInexistent(varNameExpr, defaultValue) {
try {
varNameExpr()
} catch (exc) {
defaultValue
}
}

