Groovy:如何为全局范围字段分配动态值

时间:2016-07-07 13:31:06

标签: groovy

通过使用@Field,我们可以为私有范围字段分配一些值,以便可以全局访问这些字段。

我有以下脚本:

import groovy.transform.Field;

def cli = new CliBuilder()

cli.usage = 'groovy Test.groovy -e <environment-name>'
cli.header = '\nAvailable options (use -h for help):\n'

cli.with {
    h(longOpt: 'help', 'Usage Information', required: false)
    e(longOpt: 'environment', 'Environment Name', args: 1, required: true)
}

def options = cli.parse(args)

if (!options || options.h) {    
    return
}

@Field def env = options.e

println env

当我运行时:groovy Test.groovy -e int

我收到以下错误:

Caught: java.lang.reflect.InvocationTargetException
java.lang.reflect.InvocationTargetException
        at Test.main(Test.groovy)
Caused by: groovy.lang.MissingPropertyException: No such property: options for class: Test
        at Test.<init>(Test.groovy)
        ... 1 more

但如果使用@Field def env = options.e则不使用println options.e,则会打印int

如何为全局范围的变量分配动态值?

1 个答案:

答案 0 :(得分:2)

移动它,这样就不会将分配与字段的定义联系起来......

import groovy.transform.Field;

@Field def env
def cli = new CliBuilder()

cli.usage = 'groovy Test.groovy -e <environment-name>'
cli.header = '\nAvailable options (use -h for help):\n'

cli.with {
    h(longOpt: 'help', 'Usage Information', required: false)
    e(longOpt: 'environment', 'Environment Name', args: 1, required: true)
}

def options = cli.parse(args)

if (!options || options.h) {    
    return
}

env = options.e

println env