0

I have a user input:

val method = """doReplace(doReplace("ab","a","x"),"b","y")"""

How can I invoke this method at run-time using Scala:

object test2 {

  def doReplace(str: String, oldChar: String, newChar: String) = {
    str.replace(oldChar, newChar)
  }

  def main(args: Array[String]): Unit = {

    val method = """doReplace(doReplace("ab","a","x"),"b","y")"""

  }

} 
Souvik
  • 377
  • 4
  • 16
  • 1
    it's possible to use reflection API, but you still need to do a lot of work parsing the user input to find the method name... (unless you restrict the user input a lot) – pedrorijo91 Dec 29 '18 at 18:53

1 Answers1

3

If the user should only be able to call certain methods or have a simple grammar, you may write a simple parser that uses reflection. Scala fastparse is a really great utilty.

If the user should be able to enter arbitrary scala code, you could use a scala implementation of the JSR 223 scripting api or you can compile the code at runtime as describe in this question.

Be aware that this allows to execute arbitrary code on your machine. Do not expose this interface.

Aki
  • 1,644
  • 12
  • 24