2. Agenda
â What is Reflection?
â Scala reflection Universe
â Mirrors (information providers)
â Symbols
â Some Examples
3. What is reflection?
Reflection is the ability to inspect, and possibly
even modify itself at runtime. [1]
1. Runtime reflection
2. Compile-time reflection
3. Reification
introduced in Scala 2.10
[1]http://docs.scala-lang.org/overviews/reflection/overview.html
4. (the) Universe
entry point to Scalaâs reflection
provides an interface to main types:
Types
Symbols (definitions)
Trees (abstract syntax trees)
Names (terms and type names)
Annotations
Constants
Positions (source position of tree nodes)
FlagSet (sets of flags that apply to symbol and definition
trees)
6. Mirrors
information provided by reflection accessible
through mirrors
different flavors of mirrors
Classloader Mirrors
Invoker Mirrors
obtaining special Invoker Mirrors from
Classloader Mirror
7. Types of Mirrors & their usecases
ReflectiveMirror
loading symbols by name
entry point to invoker mirrors
InstanceMirror
creating Invoker Mirrors
MethodMirrors
invoking instance methods
8. Types of Mirrors & their usecases
ClassMirror
creating invoker mirrors for constructors
ModuleMirror
getting singleton instances of objects
FieldMirror
getting/settings instance fields
9. Symbols
bindings between a name and the entity it
refers to
TypeSymbol
type, class, trait declarations
e.g. ClassSymbol
TermSymbol
val, var, def, object declarations
e.g. MethodSymbol, ModuleSymbol
10. Examples
val mirror: RuntimeMirror = universe.runtimeMirror(getClass.getClassLoader)
> res0: reflect.runtime.universe.Mirror = JavaMirror with scala.tools.nâŠ
class Reflect(x: Int)
val clz: ClassSymbol = typeOf[Reflect].typeSymbol.asClass
> res1: reflect.runtime.universe.ClassSymbol = class Reflect
def getTypeTag[T: universe.TypeTag](obj: T) = universe.typeTag[T]
val r = new Reflect(4)
val clz: ClassSymbol = getTypeTag( r).tpe.typeSymbol.asClass
> res2: reflect.runtime.universe.ClassSymbol = class Reflect
val cm: ClassMirror = mirror.reflectClass( clz)
> res3: reflect.runtime.universe.ClassMirror = class mirror for Reflect
(bound to null)
object C{ def x = 2}
val mod: ModuleSymbol = typeOf[C.type].termSymbol.asModule
> res4: reflect.runtime.universe.ModuleSymbol = object C
val mm: ModuleMirror = mirror.reflectModule( mod)
> res5: reflect.runtime.universe.ModuleMirror = module mirror for C (bound
to null)