【发布时间】:2012-06-26 23:51:10
【问题描述】:
我在返回 url 的域类中有静态方法。我需要动态构建该网址,但 g.link 不起作用。
static Map options() {
// ...
def url = g.link( controller: "Foo", action: "bar" )
// ...
}
我收到以下错误:
Apparent variable 'g' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'g' but left out brackets in a place not allowed by the grammar.
@ line 17, column 19.
def url = g.link( controller: "Foo", action: "bar" )
^
1 error
显然我的问题是我试图从静态上下文访问g,那么我该如何解决这个问题?
【问题讨论】:
-
不要在静态范围内执行此操作。使用实例方法,或者更好的是,将此代码放在服务中以便可以注入。
-
我在执行此操作时没有实例。
-
是的,我同意 OverZealous 的观点。这样做真的很糟糕。
-
@typoknig:那你做错了,非常错了。控制器不应该用于通用代码。
-
我这样做的原因是因为我正在构建一个 flexigrid。 flexigrid 将包含许多特定类型的对象,因此对我来说,该方法是静态的是有意义的。 url 是 flexigrid 所需选项的一部分。
标签: grails