0

I have an Scala application that contains several methods. I want to be able to store a list of a subset of those methods in a text file somewhere. When my application execute, I want it to read that text file execute the methods I have specified there. Any idea how to do that?

I know I can create list of functions in Scala (List[Int => Int], or something similar)that contains the method names, and then just iterate over that list. The problem is how do I dynamically create that list from the text file and get Scala to recognize I am trying to give it a method name, not just a plain text string.

Thanks.

J Calbreath
  • 2,665
  • 4
  • 22
  • 31
  • 1
    Do you have a list of predefined possible methods, or do you want to be able to have any function in your list? – Cyrille Corpet Mar 23 '17 at 13:04
  • I'm pretty sure you should use reflection. I'm not familiar enough with scala reflection, but here's a good link: http://docs.scala-lang.org/overviews/reflection/overview.html. Take a look at the section titled Accessing and Invoking Members of Runtime Types – Joe Mar 23 '17 at 13:35
  • Ideally it could be any function. I could create a list of possible methods, which does give me an idea of how to make it work. – J Calbreath Mar 23 '17 at 13:35

1 Answers1

0

If you store the method calls in proper Scala syntax in a text file, you can add a small class wrapper around them (see example below). The (in the app) call the compiler as shown in How to invoke the Scala compiler programmatically? and have the object compiled, then execute 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
    }
}
Community
  • 1
  • 1
radumanolescu
  • 4,059
  • 2
  • 31
  • 44