vendredi 9 décembre 2016

scala - delegate implementation design pattern (without reflection ?)

I would like to expose a public API (a kind of Runnable) and let users implement it, and then execute that code against our servers (given the class name containing the code to run).

Below is a snippet illustrating the issue.

The public API:

package mypackage

trait MyTrait {
  def run(i: Int) : Unit
}

A sample user's implementation:

package mypackage

object MyImpl extends MyTrait {
  override def run(i : Int) : Unit = {
    println(i)
  }
}

The server-side code running the user's code:

package mypackage

import scala.reflect.runtime.{universe => ru}

object MyTest extends App {

  val m = ru.runtimeMirror(getClass.getClassLoader)
  val module = m.staticModule("mypackage.MyImpl")
  val im = m.reflectModule(module)
  val method = im.symbol.info.decl(ru.TermName("run")).asMethod

  val objMirror = m.reflect(im.instance)
  objMirror.reflectMethod(method)(42)
}

The above code works (printing "42"), but the deisgn seems ugly to me.

What's the best way to achieve this ?

I am using Scala 2.11.8.

Thanks for your help

Aucun commentaire:

Enregistrer un commentaire