I needed to load a bunch of classes dynamically based on a configuration file. As I am a big fan of the Don’t Repeat Yourself (DRY) principle (who isn’t?!?!), I didn’t want to type/copy the same code but use a reusable function. After some playing around I came up with the following code.
def splitter = createInstance[Splitter](config.getString("downloader.dependencies.splitter"))
def merger = createInstance[Merger](config.getString("downloader.dependencies.merger"))
def cleaner = createInstance[Cleaner](config.getString("downloader.dependencies.cleaner"))
private def createInstance[T](classFQN: String) = {
val classLoader = getClass.getClassLoader
exceptionWrapper {
classLoader.loadClass(classFQN).newInstance.asInstanceOf[T]
}
}
private def exceptionWrapper[T](f: => T) = {
try {
f
} catch {
case e: ClassNotFoundException => throw e
}
}
To further improve the readability of the code I added the exception wrapper. I think it is pretty neat and readable code. What do you think? Happy coding 🙂