Loading a class dynamically using the DRY principle

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 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s