为什么这段代码在groovy中有效?

Den*_* S. 1 groovy

怎么可能this.class在类的字段声明中写入它实际上会做什么?

例如:

private static final logger = Logger.getLogger(this.class)
Run Code Online (Sandbox Code Playgroud)

PS:似乎是Schroedinbug的好地方.:)

Jus*_*per 11

在Groovy this中,静态上下文中绑定了类,您可以在其上调用静态方法.Logger.getLogger(this.class)将等同于Logger.getLogger(Class).

class C {
    static final staticThis = this
    static final thisClass  = this.getClass()
    static final someResult = this.someMethod()

    static someMethod() { 'static' }
}

assert C.staticThis == C.class
assert C.thisClass  == Class
assert C.someResult == C.someMethod()
Run Code Online (Sandbox Code Playgroud)