In the examples I have seen on Scala 2.10 reflection, the starting point is usually a known class. In the, example below, “List[Int]” is known.
scala> import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe._ scala> typeOf[List[Int]] res0: reflect.runtime.universe.Type = scala.List[Int]
What if at runtime, you just have a class name? How would you reflect that class? It turns out that I needed to:
// 1. Get a mirror
scala> val mirror = ru.runtimeMirror(getClass.getClassLoader)
mirror: reflect.runtime.universe.Mirror = ...
// 2. Convert class name into a class
scala> val clz = Class.forName("scala.collection.immutable.List")
clz: Class[_] = class scala.collection.immutable.List
// 3. Convert class into class symbol
scala> val listClassSymbol = mirror.classSymbol(clz)
listClassSymbol: reflect.runtime.universe.ClassSymbol = class List
// 4. You can now find out info about the class
scala> listClassSymbol.isTrait
res3: Boolean = false
scala> listClassSymbol.isAbstractClass
res5: Boolean = true
// 5. To find out info about it members, inheritance, etc,
// you need to convert the class symbol into a Type
scala> val listType = listClassSymbol.toType
listType: reflect.runtime.universe.Type = List[A]
scala> listType.members
res6: reflect.runtime.universe.MemberScope = Scopes(method removeDuplicates, method foreach, method toStream, method stringPrefix, method reverse, method span, method dropWhile, method takeWhile, method splitAt, method takeRight, method slice, method drop, method take, method toList, method +:, method ++, method mapConserve, method reverse_:::, method :::, method ::, method companion, constructor List, method super$sameElements, method lastIndexWhere, method indexWhere, method segmentLength, method isDefinedAt, method lengthCompare, method sameElements, method dropRight, method last, method reduceRight, method reduceLeft, method foldRight, method foldLeft, method find, method contains, method exists, method forall, method apply, method length, method $init$, method productPrefix, method...
Once you have a Type, you can use a ClassMirror to instance it.
Here’s the official document on ClassSymbol, Type and Mirror.