2016-07-07 44 views
2

通過使用@Field,我們可以給私有作用域賦予一些值,以便可以全局訪問這些字段。Groovy:如何將動態值分配給全局作用域

我有以下腳本:

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

如何將動態值分配給全局作用域變量?

+0

我的小骯髒的解決方案: https://gist.github.com/chfstudio/51e58e56abb1e29ea53a68e7fd71197e – chf

回答

1

移動它,所以你沒有分配綁在字段的定義......

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 
相關問題