Class of current static scope in scala
I'm currently constructing loggers (with configgy) like this:
class MyClass {
private val log = Logger.get(classOf[MyClass])
}
I would like to avoid repeating "MyClass" as in classOf[MyClass]
(for example I want to quickly copy paste the log definition line, without smart IDE expanding the template with the class name), but I don't want to use the dynamic class of the current object, like:
class MyClass {
private val log = Logger.get(this.getClass)
}
EDIT: because this way instances of subclasses will have the subclass class object passed to the parent logger:
class MyClass {
private val log = Logger.get(this.getClass)
def doit = log.info("doing")
}
class SubClass extends MyClass {
}
new SubClass().doit
will use the logger configured for SubClass, not MyClass as I want.
Is there a way to 开发者_如何转开发have some fixed expression which somehow yields the class which is being defined at that point?
The short answer is that Scala doesn't have a way to do that. The long answer is that you can do it, but it's an ugly hack. The hack is to use the fact that exception stack traces include the name of the static class definition where the stack trace was created. Parse and tada. But, seriously, don't do this. Or, if you do, move it to a mixin trait and modify the parsing bit to pull the class name from the appropriate spot in the trace. Also, I've only tested this in some fairly limited conditions: no guarantee that it will work everywhere.
class MyClass {
private val log = Logger get (Class forName (
new RuntimeException().getStackTrace.apply(0).toString takeWhile
(_ != '(') split "\\." dropRight 1 mkString "."))
def doit = log.info("doing")
}
Surely you can just use the protected access modifier and access it directly?
class MyClass {
protected val log = Logger.get(classOf[MyClass])
}
class SubClass extends MyClass {
}
new SubClass().doit
精彩评论