scala – 将String转换为可运行代码的方法有哪些?
发布时间:2020-12-16 09:07:52 所属栏目:安全 来源:网络整理
导读:我找不到如何将String转换为可运行的代码,例如: val i = "new String('Yo')"// conversionprintln(i) 应该打印 Yo 转换后. 我在另一篇文章中找到了以下示例: import scala.tools.nsc.interpreter.ILoopimport java.io.StringReaderimport java.io.StringWr
我找不到如何将String转换为可运行的代码,例如:
val i = "new String('Yo')" // conversion println(i) 应该打印 Yo 转换后. 我在另一篇文章中找到了以下示例: import scala.tools.nsc.interpreter.ILoop import java.io.StringReader import java.io.StringWriter import java.io.PrintWriter import java.io.BufferedReader import scala.tools.nsc.Settings object FuncRunner extends App { val line = "sin(2 * Pi * 400 * t)" val lines = """import scala.math._ |var t = 1""".stripMargin val in = new StringReader(lines + "n" + line + "nval f = (t: Int) => " + line) val out = new StringWriter val settings = new Settings val looper = new ILoop(new BufferedReader(in),new PrintWriter(out)) val res = looper process settings Console println s"[$res] $out" } 链接:How to convert a string from a text input into a function in a Scala 但似乎scala.tools不再可用了,而且我是Scala的新手,所以我无法弄清楚如何更换它. 谢谢 ! 解决方法
您可以使用Quasiquotes(实验模块)简单地执行String中包含的代码.
import scala.reflect.runtime.universe._ import scala.reflect.runtime.currentMirror import scala.tools.reflect.ToolBox // TO compile and run code we will use a ToolBox api. val toolbox = currentMirror.mkToolBox() // write your code starting with q and put it inside double quotes. // NOTE : you will have to use triple quotes if you have any double quotes usage in your code. val code1 = q"""new String("hello")""" //compile and run your code. val result1 = toolbox.compile(code1)() // another example val code2 = q""" case class A(name:String,age:Int){ def f = (name,age) } val a = new A("Your Name",22) a.f """ val result2 = toolbox.compile(code2)() REPL中的输出: // Exiting paste mode,now interpreting. import scala.reflect.runtime.universe._ import scala.reflect.runtime.currentMirror import scala.tools.reflect.ToolBox toolbox: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@69b34f89 code1: reflect.runtime.universe.Tree = new String("hello") result1: Any = hello code2: reflect.runtime.universe.Tree = { case class A extends scala.Product with scala.Serializable { <caseaccessor> <paramaccessor> val name: String = _; <caseaccessor> <paramaccessor> val age: Int = _; def <init>(name: String,age: Int) = { super.<init>(); () }; def f = scala.Tuple2(name,age) }; val a = new A("Your Name",22); a.f } result2: Any = (Your Name,22) scala> 要了解有关Quasiquotes的更多信息: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |