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"
呢?
def containingClassTypeName: String = {
val st = Thread.currentThread().getStackTrace
st(2).getClassName
}
这是一个可怕的黑客,但无论你想做什么。