我有一个 Controller ,它继承自一个带有 beforeInterceptor
的类。 .
这是我的基类。
class FooBase {
def beforeInterceptor = [action: {parentInterceptor()}]
def parentInterceptor() {
render("Snarge")
}
}
这是不工作的 Controller 版本。
class BrokenController extends FooBase
{
def beforeInterceptor = [action: {childInterceptor()}]
def childInterceptor() {
super.beforeInterceptor.action.call()
render("Bar")
}
def index = {
render("Foo")
}
}
这是一个有效的版本
class WorkingController extends FooBase
{
def beforeInterceptor = {
super.beforeInterceptor.action.call()
render("Bar")
}
def index = {
render("Foo")
}
}
当我在
WorkingController
上调用 index 时,我得到输出 SnargeBarFoo
.当我在 BrokenController
上调用 index 时我收到了 IllegalAccessError
我想我有一个有效的版本,所以我的问题更多是关于这里发生了什么?为什么一个版本可以从子类访问父类,而另一个不能?
我正在寻找的用例是能够将拦截器函数与
except
一起使用。功能。这需要在使用 map 实现拦截器时能够链接拦截器。
最佳答案
之间有区别
this.
和
this.&
以下代码有效 - 检查第三行:
class BrokenController extends FooBase
{
def beforeInterceptor = [action: {this&childInterceptor()}]
def childInterceptor() {
super.beforeInterceptor.action.call()
render("Bar")
}
def index = {
render("Foo")
}
}
文档说明了以下内容。&
Method Reference .& Get a reference to a method, can be useful for creating closures from methods
所以我不确定,但我猜它与调用方法的范围有关。也许系统创建了某种帮助器类来执行一个闭包,这导致这个类没有 super.beforeInterceptor 方法。
关于inheritance - 你如何将 beforeInterceptors 链接在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4653561/