mardi 2 juin 2015

Get runtime type of class containing instance of my class

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" 
  }
}

How can I make it so that containingClassTypeName knows well enough to return "Foo"?





Aucun commentaire:

Enregistrer un commentaire