[英]Scala: Store list of methods to execute in text file
我有一個包含幾種方法的Scala應用程序。 我希望能夠將這些方法的子集的列表存儲在某個地方的文本文件中。 當我的應用程序執行時,我希望它讀取該文本文件,執行我在那里指定的方法。 任何想法如何做到這一點?
我知道我可以在Scala中創建函數列表(List [Int => Int]或類似的東西),其中包含方法名稱,然后在該列表上進行迭代。 問題是如何從文本文件動態創建該列表,並使Scala識別出我正在嘗試給它提供一個方法名,而不僅僅是純文本字符串。
謝謝。
如果將方法調用以適當的Scala語法存儲在文本文件中,則可以在它們周圍添加一個小的類包裝器(請參見下面的示例)。 (在應用程序中)調用編譯器,如如何以編程方式調用Scala編譯器所示? 並編譯對象,然后執行ThingsToDoWhenAppStarts.methodToCallFromApp()
package com.myco.compcall
import scala.tools.nsc._
import java.io._
object MyApp {
def main(args: Array[String]): Unit = {
val fn = "/MyTextFile.txt"
val f = new File(getClass.getResource(fn).toURI)
val s = new Settings()
s.embeddedDefaults[ThingsToDoWhenAppStarts]
s.outdir.value = "target/scala-2.11/classes"
val compiler = new Global(s)
val testFiles = List(f.getAbsolutePath)
val runner = new compiler.Run()
runner.compile(testFiles)
val ftfCls = Class.forName("com.myco.compcall.FromTextFile")
val ftf = ftfCls.newInstance().asInstanceOf[ThingsToDoWhenAppStarts]
ftf.methodToCallFromApp()
}
def method1(): Unit = {
println("Method1")
}
def method2(s: String): Unit = {
println(s"Method2: $s")
}
}
abstract class ThingsToDoWhenAppStarts {
def methodToCallFromApp(): Unit
}
// ---------- ---------- ---------- //
// src/main/resources/MyTextFile.txt
package com.myco.compcall
class FromTextFile extends ThingsToDoWhenAppStarts {
def methodToCallFromApp(): Unit = {
MyApp.method1() // a call to a method defined in the app
MyApp.method2("an argument") // a call to a method defined in the app
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.