Scala Nuggets: Finding All Classes in a Package

Posted on Tuesday, August 16, 2011

3


Recently, while doing a project for one of our clients in the US, we had the opportunity to build a plugin based framework for the product. While, the details of the plugin framework are reserved as a topic of another post, in this one we would see how easy it is to find all the classes in a package using a utility provided by Clapper. The name of the utility is ClassUtil and you can get more details from their site.

Our scenario was that we should be able to discover any new plugins which are added for the product at the time when the product is initialized. For this the above utility came in pretty handy.

The simple code as you would expect in Scala is

def init() {
    val classpath = List(".").map(new File(_))
    val finder = ClassFinder(classpath)
    val classes = finder.getClasses
    val classMap = ClassFinder.classInfoMap(classes)
    val plugins = ClassFinder.concreteSubclasses("com.inphina.plugin.ProdPlugin", classMap)

    plugins.foreach {
      pluginString =>
        val plugin = Class.forName(pluginString.name).newInstance().asInstanceOf[ProdPlugin]
        pluginMap += (plugin.name -> pluginString.name)
    }
  }

As you would notice, we start from the current location and scan for all the files in that location which extend our trait called com.inphina.plugin.ProdPlugin
This, returns back a list of all classes which are extending the trait. Next, we instantiate the plugin and put it in a map for our product to consume it. There are several other ways in which you can filter your classes and you would get more details here.

If you are using SBT 0.10x then you can add the dependency in build.sbt with the following

name := "InphinaProductManager"
version := "1.0"
organization := "com.inphina.prod"
scalaVersion := "2.9.0-1"

resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"

libraryDependencies ++= Seq(
  "se.scalablesolutions.akka" % "akka-actor" % "1.1.3",
  "se.scalablesolutions.akka" % "akka-typed-actor" % "1.1.3",
  "se.scalablesolutions.akka" % "akka-amqp" % "1.1.3",
  "se.scalablesolutions.akka" % "akka-testkit" % "1.1.3"
)

libraryDependencies += "org.scalatest" % "scalatest_2.9.0" % "1.6.1"

libraryDependencies += "org.clapper" % "classutil_2.9.0" % "0.3.6"

A word of caution, finding classes in such a way is an involved process and might not be performant for your scenario. For our case, we have to do it only once at the start of the product and the number of plugins would not exceed a score.

Advertisements
Posted in: Scala