Why does Scala reflection work inside an object but not at the top level of a script?

百般思念 提交于 2019-12-25 02:58:54

问题


This script uses reflection to find the type signature of a constructor. It contains the same code inside an object and at the top level:

// Scala 2.11.1
case class Dirigible(cubicFeet: Int)

object Object {
  val u = scala.reflect.runtime.universe
  val ctor = u.weakTypeOf[Dirigible].decl(u.termNames.CONSTRUCTOR).typeSignature
  def run() {
    println(ctor)
  }
}

Object.run()

val u = scala.reflect.runtime.universe
val ctor = u.weakTypeOf[Dirigible].decl(u.termNames.CONSTRUCTOR).typeSignature
println(ctor)

Here is the output:

(cubicFeet: Int)$anon.this.Dirigible
<notype>

Why does the top-level code fail while the code inside Object works?

The same failure occurs if I put the println inside a top-level def and call it from the top level.

The top-level code works if I run the file in the REPL via scala -i refltest.scala. That's to be expected, since the REPL puts everything into an object. What I don't understand is, why does code's being inside an object affect the results of reflection?


回答1:


The script runner wraps your code in a local anonymous class; your code is run as part of the initializer.

I don't know why that breaks reflection, but it's a duplicate of this question from a couple of years ago. That was edited to say the problem was fixed, but I don't see it working.

As a workaround, wrap your code in a block:

locally {
val u = scala.reflect.runtime.universe
val ctor = u.weakTypeOf[Dirigible].decl(u.termNames.CONSTRUCTOR).typeSignature
println(ctor)
}

Maybe it has to do with init order and how the local class is compiled.



来源:https://stackoverflow.com/questions/23843338/why-does-scala-reflection-work-inside-an-object-but-not-at-the-top-level-of-a-sc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!