反射工具箱在 Scala 2.11 中工作在 Scala 2.12 中不起作用 [英] Reflect Toolbox worked in Scala 2.11 not working in Scala 2.12
问题描述
这段在 Scala 2.11 中有效的代码在 2.12 中无效:
This code that works in Scala 2.11 doesn't work in 2.12:
import scala.reflect.runtime.universe
import scala.tools.reflect.ToolBox
val tb = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
tb.eval(tb.parse("""println("hello!")"""))
我收到以下错误,2.12 有什么变化?
I get the error below, what changed in 2.12?
线程main"中的异常java.lang.AbstractMethodError:scala.reflect.internal.SymbolPairs$Cursor.matches(Lscala/reflect/internal/Symbols$Symbol;)Z
Exception in thread "main" java.lang.AbstractMethodError: scala.reflect.internal.SymbolPairs$Cursor.matches(Lscala/reflect/internal/Symbols$Symbol;)Z
注意:我必须添加到类路径 scala-compiler-2.12.2.jar
Note: I had to add to the classpath scala-compiler-2.12.2.jar
推荐答案
是否有可能您将项目更新到 Scala 2.12 但在类路径上留下了对 scala-compiler
2.11 的依赖?
Is it possible, that you updated your project to Scala 2.12 but left a dependency on scala-compiler
2.11 on your classpath ?
2.12 中没有任何更改,与您的代码有关.为了让您的代码工作,您必须依赖于 scala-compiler.
Nothing changed in 2.12, with relation to your code. In order for your code to work, you must have a dependency on scala-compiler.
这是一个带有 Scala 2.11 的 SBT 项目,没有 scala-compiler
依赖:
Here is a SBT project with Scala 2.11, without scala-compiler
dependency:
name := "q53391593"
organization := "sk.ygor.stackoverflow"
version := "1.0-SNAPSHOT"
scalaVersion := "2.11.12"
您的代码无法编译:object runtime is not a member of package reflect
, object tools is not a member of package scala
, not found: value宇宙
Your code does not compile: object runtime is not a member of package reflect
, object tools is not a member of package scala
, not found: value universe
你需要添加对scala-compiler
的依赖:
name := "q53391593"
organization := "sk.ygor.stackoverflow"
version := "1.0-SNAPSHOT"
scalaVersion := "2.12.6"
libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value
这将在您的类帕特上放置两个额外的 jar:scala-compiler:2.12.6:jar
和 scala-reflect:2.12.6:jar
.如果您不使用 SBT,请确保您自己包含它们.
This will put two additional jars on your classpat: scala-compiler:2.12.6:jar
and scala-reflect:2.12.6:jar
. If you are not using SBT, make sure, that you include them by yourself.
另外,请注意使用 scalaVersion.value
来指定库的版本.这可以防止将不兼容版本的 Scala 库混合在一起.
Also, note the usage of scalaVersion.value
to specify the version of the library. This prevents from mixing together incompatible versions of Scala libraries.
这篇关于反射工具箱在 Scala 2.11 中工作在 Scala 2.12 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!