2016-11-10 25 views
1

ソースコード(クラスオブジェクト)の文字列を解析して実行時にオブジェクトにコンパイルできるスカラー関数を実装したいと考えています。Scala Parse Stringクラスと実行時コンパイル

たとえば、これまでに試した機能です。私の目標は、実行時環境でコンパイルして実行することです。コンストラクタまたはその関数を使用できます。このコードには実行時エラーがありますが、リフレクションクラスのエラーを修正する方法はわかりません。ありがとう!

object test { 
     def main(args: Array[String]): Unit = { 
      val m = universe.runtimeMirror(getClass.getClassLoader) 
      val tb = m.mkToolBox() 
      val clazz = tb.compile(tb.parse("class insideclass {\n val model_field = 5\n def insideclass(model: Int) = {\n  val model_field = model \n } \n\n def test() : Int = {\n  model_field\n }\n\n}\nscala.reflect.classTag[insideclass].runtimeClass"))().asInstanceOf[Class[_]] 
      val classinside = universe.typeOf[Class[_]].typeSymbol.asClass 
      val ctor = universe.typeOf[Class[_]].declaration(universe.nme.CONSTRUCTOR).asMethod 
      val cm=m.reflectClass(classinside) 
      val ctorm=cm.reflectConstructor(ctor) 
      println(ctorm(10).test()) 
     } 
    } 

答えて

1

外部コンパイラは、クラス定義として "insideclass"が存在しないことを知りません。 1つの解決策は、内部クラスが、コンパイラの内部と外部の両方に知られているいくつかの他のクラスを拡張することです。たとえば、Function [Int、Int]です。この場合、「テスト」メソッドの名前を「適用」に変更する必要があります。

val clazz = tb.compile(tb.parse("class PersonData(x:Int) extends Function[Int, Int] {\n val allen = x.toInt\n\n override def apply(x:Int):Int = allen}\n scala.reflect.classTag[PersonData].runtimeClass"))().asInstanceOf[Class[_]] 

val ctor = clazz.getDeclaredConstructors()(0) 

val instance = ctor.newInstance(new Integer(1)) 
// this cast can succeed because the outside knows what is Function[Int, Int] 
println(instance.asInstanceOf[Function[Int, Int]].apply(1)) 
関連する問題