Search code examples
scalareflectionscala-reflect

Instance name at runtime with the Scala Reflection API


Lets start with the following example:

class Foo {
  override def toString = ???
}

val instanceName = new Foo()
println(instanceName) // Should print "instanceName"

Using the Scala Reflection API (or any other method), how can I get the name of the instance of a class at runtime ? How to get this information from the AST ?

Same question but for Java: Java Reflection: How to get the name of a variable?


Solution

  • I'm sorry, but the question doesn't really make sense. I'll try to explain why.

    Imagine that suitable magic existed that would allow toString to do as you wish. Now let's add a few more lines:

    class Foo {
      override def toString = ???
    }
    
    val instanceName = new Foo()
    val larry = instanceName
    val moe = larry
    val curly = moe
    println(instanceName.toString)
    

    What would you expect to be printed -- instanceName? larry? moe? curly? All of those identifiers are bound to the same object. When toString executes, the variable used to refer to the object is gone -- the object reference is in this and that's all there is.

    An object knows nothing about which identifiers -- representing data on the stack or even in other objects -- refer to it. Not only does the toString method not have access to the name of the variable, there really isn't a single variable for it to know about.