<%= NewRelic::Agent.browser_timing_header rescue "" %>

David van Geest

Software, Life, and Stuff I Couldn't Find on the Internet

Finding concrete subtypes in Scala

| Comments

On my current project, which is written in Scala, I needed a way to dynamically find all of the concrete subclasses of a given class, found in a given package.

While this is possible using the Scala Reflection API, this bug did not give me confidence that it would work correctly. Instead, I turned to the library mentioned in the comments, namely Reflections, which is written in Java and can be found here.

Using this library made the task quite straightforward. In the code below, I’m finding all concrete subclasses of Attribute[_] found in the com.example package.

1
2
3
4
5
6
7
8
9
10
11
12
import java.lang.reflect.Modifier
import org.reflections.Reflections

object Attribute {
  private val reflections = new Reflections("com.example")
  private val allAttributeClasses = reflections.getSubTypesOf(classOf[Attribute[_]])
  private val concreteAttributeClasses = allAttributeClasses filter { klass =>
    !Modifier.isAbstract(klass.getModifiers)
  }

  // do some useful stuff with the list of subclasses
}

Note that I’m making use of the standard Java reflection API to check whether a class is concrete or not.

In my next post I’ll talk about doing some interesting things with this list of subclasses!

Comments