挖掘时似乎这是一个敏感问题。
class TestNames {
private[this] lazy val _name: String = this.getClass.getName.split("\\.").last
def name: String = _name
}
class Parent extends TestNames
class Parent2 extends Parent
class ClassNameExtraction extends FlatSpec {
it should "correctly extract the table name" in {
object TestNames extends TestNames
assert(TestNames.name === "TestNames")
}
it should "correctly extract the parent name" in {
object Parent extends Parent
assert(Parent.name === "Parent")
}
it should "correctly extract the column names" in {
object Parent2 extends Parent2
assert((Parent2.name === "Parent2"))
}
}
我可以看到有一个简单的模式:$$annonfun$number$ + ACTUAL_CLASS_NAME + $number$
。
有没有更简单的方法呢?
更新
在没有继承的情况下工作:
import scala.reflect.ClassTag
class SomeClass {
private[this] lazy val _name: String = implicitly[ClassTag[this.type]].runtimeClass.getSimpleName
def name: String = _name
}
但是这会在子类中返回相同的名称:
class SomeOtherClass extends SomeClass {}
object SomeOtherClass extends SomeOtherClass
SomeOtherClass.name// is still SomeClass
答案 0 :(得分:2)