0
votes

I would like to load some scala class at runtime, the class are presents in my scala project. More precisely, in the root folder of my project, I have the TmpCaseClass.scala :

class TmpHBaseCaseClass(val adresse:String,val age:Int,val nom:String,val id:Int,val salaire:Float)

I would like to compile it and use it at run time using toolBox like this :

val tb = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
  val clazz = tb.compile(tb.parse("./TmpCaseClass.scala"))().asInstanceOf[Class[_]]
  val ctor = clazz.getDeclaredConstructors()(0)
  val instance = ctor.newInstance()

But I encounter the follwing error :

Exception in thread "main" scala.tools.reflect.ToolBoxError: reflective compilation has failed:

illegal start of definition at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.throwIfErrors(ToolBoxFactory.scala:316) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.parse(ToolBoxFactory.scala:291) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$$anonfun$parse$1.apply(ToolBoxFactory.scala:417) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$$anonfun$parse$1.apply(ToolBoxFactory.scala:414) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$withCompilerApi$.liftedTree2$1(ToolBoxFactory.scala:355) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$withCompilerApi$.apply(ToolBoxFactory.scala:355) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.parse(ToolBoxFactory.scala:414) at Main$.delayedEndpoint$Main$1(Main.scala:17) at Main$delayedInit$body.apply(Main.scala:13) at scala.Function0$class.apply$mcV$sp(Function0.scala:34) at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12) at scala.App$$anonfun$main$1.apply(App.scala:76) at scala.App$$anonfun$main$1.apply(App.scala:76) at scala.collection.immutable.List.foreach(List.scala:381) at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35) at scala.App$class.main(App.scala:76) at Main$.main(Main.scala:13) at Main.main(Main.scala)

The line 17 (where the error happens) corresponds to :

val clazz = tb.compile(tb.parse("./TmpCaseClass.scala"))().asInstanceOf[Class[_]]

How could I get rid of this error ?

1

1 Answers

0
votes

1) Try to parse file contents, instead of file name.

2) Also you wont be able to cast to Class, since compilation returns Unit. You might want to put another line like scala.reflect.classTag[TmpCaseClass].runtimeClass. You can also get tree (AST) as a result of tb.parse, if that's what you need.