scala 中当前静态作用域的类
我目前正在构造记录器(使用 configgy),如下所示:
class MyClass {
private val log = Logger.get(classOf[MyClass])
}
我想避免重复“MyClass”,如 classOf[MyClass]
(例如,我想快速复制粘贴日志定义行,而不需要智能IDE用类名扩展模板),但我不想使用当前对象的动态类,例如:
class MyClass {
private val log = Logger.get(this.getClass)
}
编辑:因为这样子类的实例将把子类类对象传递给父记录器:
class MyClass {
private val log = Logger.get(this.getClass)
def doit = log.info("doing")
}
class SubClass extends MyClass {
}
new SubClass().doit
将使用为 SubClass 配置的记录器,而不是我想要的 MyClass。
有没有办法有一些固定的表达式,以某种方式产生当时正在定义的类?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简而言之,Scala 没有办法做到这一点。长的答案是你可以做到,但这是一个丑陋的黑客。破解方法是利用异常堆栈跟踪包含创建堆栈跟踪的静态类定义的名称这一事实。解析和塔达。但是,说真的,不要这样做。或者,如果这样做,请将其移动到 mixin 特征并修改解析位以从跟踪中的适当位置提取类名称。另外,我只在一些相当有限的条件下对此进行了测试:不能保证它在任何地方都能工作。
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.
您当然可以使用 protected 访问修饰符并直接访问它吗?
Surely you can just use the protected access modifier and access it directly?