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")"""

  }

} 
1
  • 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) Commented Dec 29, 2018 at 18:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.