groovy - 访问静态范围内的全局变量

标签 groovy

有没有办法从同一脚本中声明的类的静态方法访问脚本中声明的全局变量?

例如

def s = "12345"

class MyClass {
    static def method() {
        println s
    }
}

因为这样它就会失败并出现错误

You attempted to reference a variable in the binding or an instance variable from a static context

这是预期的。

最佳答案

这个问题有一个相关的讨论:

Groovy scope - how to access script variable in a method

相关的是,两个问题都涉及在类中使用全局变量,但这个问题有所不同,因为您正在寻求使用静态方法来改变传递脚本实例或绑定(bind)的方式(两种选择)。

传递脚本实例

import groovy.transform.Field

@Field def s = "12345"

class MyClass {
    static def method(si) {      
      return si.s
    }
}

assert MyClass.method(this) == "12345"

传递脚本的绑定(bind)

s = "12345" // NOTE: no 'def'

class MyClass {
    static def method(b) {      
      return b.s
    }
}

assert MyClass.method(binding) == "12345"

关于groovy - 访问静态范围内的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35417969/

相关文章:

maven - Groovy Grape 从哪里获取依赖项?

groovy - 使用 groovy 脚本创建可执行 jar

java - md5 和盐

grails - 查找groovy/grails属性的类型

gradle - Grails “war”调用未将额外的属性传递给Gradle

json - 从 mule esb 中的 JSON 中提取所有特定字段

Grails GORM 和枚举

groovy - 如何在 Groovy 中同时使用 GroupBy 和 Sum?

mongodb - MongoTimeoutException 消息 : Timed out while waiting to connect after 10000 ms

Groovy 闭包、def 与类型化返回值