问题
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!")"""))
I get the error below, what changed in 2.12?
Exception in thread "main" java.lang.AbstractMethodError: scala.reflect.internal.SymbolPairs$Cursor.matches(Lscala/reflect/internal/Symbols$Symbol;)Z
Note: I had to add to the classpath scala-compiler-2.12.2.jar
回答1:
Is it possible, that you updated your project to Scala 2.12 but left a dependency on scala-compiler
2.11 on your classpath ?
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.
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"
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
You need to add the dependency on scala-compiler
:
name := "q53391593"
organization := "sk.ygor.stackoverflow"
version := "1.0-SNAPSHOT"
scalaVersion := "2.12.6"
libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value
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.
Also, note the usage of scalaVersion.value
to specify the version of the library. This prevents from mixing together incompatible versions of Scala libraries.
来源:https://stackoverflow.com/questions/53391593/reflect-toolbox-worked-in-scala-2-11-not-working-in-scala-2-12