下面的代码片段演示了我的问题:
import java.util.timer.*
s = "Hello"
println s
class TimerTaskExample extends TimerTask {
public void run() {
//println new Date()
println s
}
}
int delay = 5000 // delay for 5 sec.
int period = 10000 // repeat every sec.
Timer timer = new Timer()
timer.scheduleAtFixedRate(new TimerTaskExample(), delay, period) 在我的TimerTaskExample实现中,我想访问在“全局”脚本作用域中创建的s。但我得到了下面的线索:
Hello
Exception in thread "Timer-2"
groovy.lang.MissingPropertyException: No such property: s for class: TimerTaskExample
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.callsite.GetEffectivePogoPropertySite.getProperty(GetEffectivePogoPropertySite.java:86)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
at TimerTaskExample.run(ConsoleScript2:8)我尝试了谷歌,但没有找到一个解决方案。
非常感谢!
Yu SHen
发布于 2014-02-03 11:58:26
尽管在绑定中定义了s(不带def),但在脚本中定义的类中无法访问它。要访问TimerTaskExample类中的,可以执行以下操作:
class TimerTaskExample extends TimerTask {
def binding
public void run() {
println binding.s
}
}
new TimerTaskExample(binding:binding)发布于 2011-12-25 22:50:38
Groovy本身没有“全局”作用域;在类中保持这样的“全局”是最干净的,定义为静态finals,就像在Java中一样:
public class Constants {
static final String S = "Hello"
}
println Constants.S
class TimerTaskExample extends TimerTask {
public void run() {
println Constants.S
}
} 发布于 2011-12-26 03:12:03
看起来您使用的是Groovy脚本。
方法唯一可以访问的内容是:
由基类定义的
脚本允许使用未声明的变量(没有def),在这种情况下,假设这些变量来自脚本的绑定,如果还不存在,则将其添加到绑定中。
name = 'Dave'
def foo() {
println name
}
foo()对于每个脚本,Groovy都会生成一个扩展groovy.lang.Script的类,该类包含一个main方法,以便Java可以执行它。在我的示例中,我只有一个类:
public class script1324839515179 extends groovy.lang.Script {
def name = 'Dave'
def foo() {
println name
}
...
}您的示例中发生了什么?您有两个类,绑定变量在Script类中。TimerTaskExample对s一无所知
public class script1324839757462 extends groovy.lang.Script {
def s = "Hello"
...
}
public class TimerTaskExample implements groovy.lang.GroovyObject extends java.util.TimerTask {
void run() {
println s
}
...
}https://stackoverflow.com/questions/8630043
复制相似问题