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)
精彩评论