简体   繁体   English

在 Groovy 脚本中使用 @Field 变量

[英]Using of @Field variable in Groovy script

I have a script with a global variable in my Groovy script I have a problem using it inside a function.我的 Groovy 脚本中有一个带有全局变量的脚本 我在 function 中使用它时遇到问题。 May I know the reason or the right way?我可以知道原因或正确的方法吗? I'm gonna be using it for a logger.我打算用它来做记录器。 Other primitive data types can be accessed but this, I can't.可以访问其他原始数据类型,但我不能。

@Field def log = Logger.getLogger("NameOfLogger")

log.info("TEST")

testFunction()

private void testFunction() {
 //cannot use the log variable here
}

I know now the cause.我现在知道原因了。 It's because I was declaring it as def But I still don't know the real reason why def can't be used.这是因为我将它声明为def但我仍然不知道def不能使用的真正原因。

The following code works for me (I haven't tried with log but used online groovy console):以下代码对我有用(我没有尝试使用日志,但使用了在线 groovy 控制台):

import groovy.transform.Field
import groovy.transform.Canonical

@Canonical
class Person {
   String name
   int age
}

@Field person = new Person("John", 30)
println "Global $person"

testFunction()  

private void testFunction() {
   println "Inside method: $person"
}​

Output: Output:

Global Person(John, 30)
Inside method: Person(John, 30)

So make sure you have proper imports first of all所以首先确保你有正确的进口

Now, it worth mentioning that groovy creates an implicit class and Field annotation alters the scope of the global variable and moves it to be a field of that implicit class so that both person and testFunction will both belong to this class and there won't be a problem to access the field from within the method. Now, it worth mentioning that groovy creates an implicit class and Field annotation alters the scope of the global variable and moves it to be a field of that implicit class so that both person and testFunction will both belong to this class and there won't be从方法内访问字段的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM