【问题标题】:How can I determine if a variable exists from within the Groovy code running in the Scripting Engine?如何确定在脚本引擎中运行的 Groovy 代码中是否存在变量?
【发布时间】:2017-07-16 20:14:11
【问题描述】:

如何确定在脚本引擎中运行的 Groovy 代码中是否存在变量?

变量是ScriptEngine's put method放的

【问题讨论】:

    标签: java jenkins groovy scripting java-scripting-engine


    【解决方案1】:

    脚本引擎注入的变量保存在 binding.variables,所以你可以例如检查名为xx的变量:

    if (binding.variables["xx"]) ...
    

    【讨论】:

    • 在我的上下文 (Jenkins) 中,我得到了错误:org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not allowed to use method groovy.lang.Binding getVariables。另一个答案也不起作用,但这不是安全问题。
    • 这是一个 Jenkins 问题。也许你应该问一个新问题并用 Jenkins 标签标记它。
    • @andrewlorien 如果你发现了这样的错误,你可以去 Jenkins 设置,“In-process Script Approval”并批准这个脚本。
    【解决方案2】:

    groovy.lang.Script 中有一个方法public Binding getBinding()。另请参阅 groovy.lang.Binding 和方法 public boolean hasVariable(String name)

    因此您可以简单地检查变量是否存在

    if (binding.hasVariable('superVariable')) {
    // your code here
    }
    

    【讨论】:

      【解决方案3】:
      // Example usage: defaultIfInexistent({myVar}, "default")
      def defaultIfInexistent(varNameExpr, defaultValue) {
          try {
              varNameExpr()
          } catch (exc) {
              defaultValue
          }
      }
      

      【讨论】:

      • 这种方法更好,因为它可以在 Jenkins 安全沙箱中运行。
      【解决方案4】:

      您可以使用'contains' List 方法检查变量是否存在:

      if (list.contains(var)) {
      // your code
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-29
        • 1970-01-01
        • 1970-01-01
        • 2017-05-03
        相关资源
        最近更新 更多