简体   繁体   中英

Scala dynamic class management

I would like to know if the following is possible in Scala (but I think the question can be applied also to Java):

  • Create a Scala file dynamically (ok, no problem here)
  • Compile it (I don't think this would be a real problem)
  • Load/Unload the new class dynamically

Aside from knowing if dynamic code loading/reloading is possible (it's possible in Java so I think it's feasible also in Scala) I would like also to know the implication of this in terms of performance degradation (I could have many many classes, with no name clash but really many of them!).

TIA!

PS: I know other questions about class loading in Scala exist, but I haven't been able to find an answer about performance!

Yes, everything you want to do is certainly possible. You might like to take a look at ScalaMock , which is an example of creating Scala source code dynamically. And at SBT which is an example of calling the compiler from code. And then there are many different systems that load classes dynamically - look at the documentation for loadLibrary as a starting point.

But, depending on what you want to achieve, you might like to look at Scala Macros instead. They provide the same kind of flexibility as you would get by generating source code and then compiling it, but without many of the downsides of that approach. The original version of ScalaMock used to work by generating source code, but I'm in the process of moving to using macros instead .

It's all possible in Scala, as is clearly demonstrated by the REPL. It's even going to be relatively easy with Scala 2.10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM