获取包含我的类实例的运行时类型

时间:2015-06-02 19:18:03

标签: scala reflection types

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"

1 个答案:

答案 0 :(得分:1)

def containingClassTypeName: String = {
  val st = Thread.currentThread().getStackTrace
  st(2).getClassName
}

这是一个糟糕的黑客,但你正在尝试做的事情也是如此。