mercredi 11 février 2015

Using Scala Reflection for a plugin architecture

I'm building an application Scala that uses a plugin architecture, and I'm trying to load plugins in at runtime. Currently, my plugin loader code is:



import org.clapper.classutil.ClassFinder

object PluginManager extends PluginManager {
val plugins = new mutable.HashMap[String, Plugin]()
val pluginFolder = new File("plugins")

def init(): Unit = {
val pluginJars = pluginFolder.listFiles.filter(_.getName.endsWith(".jar"))
val classpath = List(new File(".")) ++ pluginJars
val finder = ClassFinder(classpath)
val classes = finder.getClasses()
val classMap = ClassFinder.classInfoMap(classes.iterator)
val pluginsToLoad = ClassFinder.concreteSubclasses("org.narrativeandplay.hypedyn.plugins.Plugin", classMap)

val loader = new URLClassLoader(pluginJars.map({ f => new URL(s"file:${f.getAbsolutePath}") }), ClassLoader.getSystemClassLoader)

pluginsToLoad.foreach {
pluginString =>
val plugin = loader.loadClass(pluginString.name).newInstance().asInstanceOf[Plugin]
plugins += plugin.name -> plugin
}
}
}


(based on http://ift.tt/1CXVk2W).


I had to use the URLClassLoader because my plugin JARs weren't on the classpath when the application started


I was wondering if it's possible to use the Scala Reflection API to replace my use of the URLClassLoader, and if so, how should I do so?






Aucun commentaire:

Enregistrer un commentaire