开发者

How comes this code works in groovy?

How comes that it is possible to write this.class in the fields declaration of a class and it will actually do what is expected?

E.g.:

private static final开发者_如何学Go logger = Logger.getLogger(this.class)

P.S.: Seems like a great place for Schroedinbug. :)


In Groovy this is bound to the class in a static context, and you can call static methods on it. Logger.getLogger(this.class) would be equivalent to just 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()


Justin's answer is correct, in a static context this is bound to the Class object of the current class, Therefore, you can replace the code above with:

private static final logger = Logger.getLogger(this)

which you can safely copy-paste from one class to another, unlike:

private static final logger = Logger.getLogger(MyClass.class)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜