object GetTypeNameOfClassContainingSomeInstance {
implicit class GetsTypeNameOfContainingClass(x: Any) {
def containingClassTypeName: String = ???
}
}
class Foo {
import GetTypeNameOfClassContainingSomeInstance._
def foo(x: Any): Unit = {
println(s"${x.containingClassTypeName} owns this ${x.getClass}: $x")
// should print something like "Foo owns this <class of x>: x"
}
}
我如何才能使containingClassTypeName
足够清楚地回复"Foo"
?
答案 0 :(得分:1)
def containingClassTypeName: String = {
val st = Thread.currentThread().getStackTrace
st(2).getClassName
}
这是一个糟糕的黑客,但你正在尝试做的事情也是如此。