Reflection Library for the Scala Programming Language providing runtime reflection capabilities and metaprogramming support
npx @tessl/cli install tessl/maven-org-scala-lang--scala-reflect@2.13.0Scala Reflection Library provides comprehensive runtime and compile-time reflection capabilities for the Scala programming language. It enables programs to inspect, access, and modify their own structure and behavior at runtime, supporting advanced metaprogramming techniques including macro development, serialization frameworks, dependency injection systems, and dynamic code generation.
org.scala-lang:scala-reflect:2.13.16libraryDependencies += "org.scala-lang" % "scala-reflect" % "2.13.16"import scala.reflect.runtime.universe._
import scala.reflect.runtime.{currentMirror => cm}For macro development:
import scala.reflect.macros.blackbox.Context
// or for whitebox macros:
import scala.reflect.macros.whitebox.Contextimport scala.reflect.runtime.universe._
import scala.reflect.runtime.{currentMirror => cm}
// Get type information
val tpe = typeOf[String]
println(s"Type: $tpe")
// Runtime reflection on instances
case class Person(name: String, age: Int)
val person = Person("Alice", 25)
// Get class mirror
val classMirror = cm.reflectClass(typeOf[Person].typeSymbol.asClass)
// Create new instance
val ctor = typeOf[Person].decl(termNames.CONSTRUCTOR).asMethod
val ctorMirror = classMirror.reflectConstructor(ctor)
val newPerson = ctorMirror("Bob", 30).asInstanceOf[Person]
// Field access
val instanceMirror = cm.reflect(person)
val nameFiled = typeOf[Person].decl(TermName("name")).asTerm
val fieldMirror = instanceMirror.reflectField(nameFiled)
println(s"Name: ${fieldMirror.get}")
// Method invocation
class Calculator {
def add(x: Int, y: Int): Int = x + y
}
val calc = new Calculator
val calcMirror = cm.reflect(calc)
val addMethod = typeOf[Calculator].decl(TermName("add")).asMethod
val methodMirror = calcMirror.reflectMethod(addMethod)
val result = methodMirror(2, 3)
println(s"Result: $result")The Scala Reflection Library is organized around several key components:
scala.reflect.api.Universe)scala.reflect.runtime.*)scala.reflect.macros.*)scala.reflect.api.Symbols)scala.reflect.api.Types)scala.reflect.api.Trees)scala.reflect.api.Mirrors)Core runtime reflection functionality for inspecting types, creating instances, invoking methods, and accessing fields at runtime.
object universe extends scala.reflect.api.JavaUniverse
def runtimeMirror(classLoader: ClassLoader): RuntimeMirror
trait RuntimeMirror extends ReflectiveMirror {
def staticClass(fullName: String): ClassSymbol
def staticModule(fullName: String): ModuleSymbol
def reflect(obj: Any): InstanceMirror
}Comprehensive type system representation enabling type inspection, comparison, member lookup, and type transformations.
trait Types { self: Universe =>
type Type >: Null <: TypeApi
trait TypeApi { this: Type =>
def =:=(that: Type): Boolean
def <:<(that: Type): Boolean
def members: MemberScope
def member(name: Name): Symbol
def dealias: Type
def widen: Type
def erasure: Type
}
}Symbol representation for all definitions including classes, methods, fields, and modules with complete metadata access.
trait Symbols { self: Universe =>
type Symbol >: Null <: SymbolApi
type TypeSymbol >: Null <: TypeSymbolApi with Symbol
type TermSymbol >: Null <: TermSymbolApi with Symbol
type MethodSymbol >: Null <: MethodSymbolApi with TermSymbol
type ClassSymbol >: Null <: ClassSymbolApi with TypeSymbol
type ModuleSymbol >: Null <: ModuleSymbolApi with TermSymbol
trait SymbolApi {
def name: Name
def info: Type
def owner: Symbol
def isPrivate: Boolean
def isProtected: Boolean
def isPublic: Boolean
}
}Mirror system providing entry points for reflective operations including instance creation, method invocation, and field access.
trait Mirrors { self: Universe =>
type Mirror >: Null <: MirrorApi
type InstanceMirror >: Null <: InstanceMirrorApi
type MethodMirror >: Null <: MethodMirrorApi
type FieldMirror >: Null <: FieldMirrorApi
type ClassMirror >: Null <: ClassMirrorApi
type ModuleMirror >: Null <: ModuleMirrorApi
trait InstanceMirrorApi {
def reflectMethod(method: MethodSymbol): MethodMirror
def reflectField(field: TermSymbol): FieldMirror
}
trait MethodMirrorApi {
def apply(args: Any*): Any
}
}Mirrors and Reflective Operations
AST representation and manipulation for compile-time and runtime tree processing, reification, and code generation.
trait Trees { self: Universe =>
type Tree >: Null <: TreeApi
trait TreeApi {
def pos: Position
def tpe: Type
def symbol: Symbol
def children: List[Tree]
def duplicate: Tree
}
def reify[T](expr: T): Expr[T]
}Type tag system for preserving and accessing type information at runtime, enabling type-safe operations.
trait TypeTags { self: Universe =>
type TypeTag[T] >: Null <: WeakTypeTag[T]
type WeakTypeTag[T] >: Null <: WeakTypeTagApi[T]
trait WeakTypeTagApi[T] {
def tpe: Type
def in[U <: Universe with Singleton](otherMirror: scala.reflect.api.Mirror[U]): U#WeakTypeTag[T]
}
def typeOf[T: TypeTag]: Type
def weakTypeOf[T: WeakTypeTag]: Type
}Type Tags and Type Information
Compile-time reflection contexts for macro development including blackbox and whitebox macro support.
package scala.reflect.macros {
package blackbox {
trait Context extends scala.reflect.macros.Aliases
with scala.reflect.macros.Enclosures
with scala.reflect.macros.Names
with scala.reflect.macros.Reifiers
with scala.reflect.macros.Typers
with scala.reflect.macros.Universe {
val universe: Universe
val mirror: universe.Mirror
def prefix: Expr[_]
}
}
package whitebox {
trait Context extends blackbox.Context {
// Additional whitebox capabilities
}
}
}Typed AST wrappers and reification system for converting between runtime values and compile-time AST representations.
trait Exprs { self: Universe =>
type Expr[+T] >: Null <: ExprApi[T]
trait ExprApi[+T] {
def tree: Tree
def staticType: Type
def actualType: Type
def splice: T
}
}Annotation support for both Java and Scala annotations on definitions and types.
trait Annotations { self: Universe =>
type Annotation >: Null <: AnyRef with AnnotationApi
val Annotation: AnnotationExtractor
abstract class AnnotationExtractor {
def apply(tree: Tree): Annotation
}
trait AnnotationApi {
def tree: Tree
}
}Type classes for converting between Scala values and their AST representations.
trait Liftables { self: Universe =>
trait Liftable[T] {
def apply(value: T): Tree
}
object Liftable extends StandardLiftableInstances {
def apply[T](f: T => Tree): Liftable[T]
}
trait Unliftable[T] {
def unapply(tree: Tree): Option[T]
}
object Unliftable extends StandardUnliftableInstances {
def apply[T](pf: PartialFunction[Tree, T]): Unliftable[T]
}
}String interpolators for AST construction and pattern matching.
trait Quasiquotes { self: Universe =>
implicit class Quasiquote(ctx: StringContext) {
object q extends api // expressions and statements
object tq extends api // types
object cq extends api // case definitions
object pq extends api // patterns
object fq extends api // format strings
protected trait api {
def apply[A >: Any](args: A*): Tree
def unapply(scrutinee: Any): Any
}
}
}Pretty-printing support for reflection objects and ASTs.
trait Printers { self: Universe =>
trait TreePrinter {
def print(args: Any*): String
}
def show(any: Any): String
def showRaw(any: Any): String
}Low-level internal operations for advanced reflection use cases.
trait Internals { self: Universe =>
val internal: InternalApi
trait InternalApi {
def reificationSupport: ReificationSupportApi
def captureVariable(vble: Symbol): Unit
def referenceCapturedVariable(vble: Symbol): Tree
}
}Compile-time constant value representation and manipulation.
trait Constants { self: Universe =>
type Constant >: Null <: ConstantApi
trait ConstantApi {
def value: Any
def tpe: Type
def isNaN: Boolean
def convertTo(pt: Type): Constant
}
}Symbol modifier flags for visibility, mutability, and other properties.
trait FlagSets { self: Universe =>
type FlagSet >: Null <: FlagSetApi
trait FlagSetApi {
def |(other: FlagSet): FlagSet
def &(other: FlagSet): FlagSet
def isEmpty: Boolean
}
val Flag: FlagValues
trait FlagValues {
val PRIVATE: FlagSet
val PROTECTED: FlagSet
val ABSTRACT: FlagSet
val FINAL: FlagSet
val IMPLICIT: FlagSet
val LAZY: FlagSet
val CASE: FlagSet
val SEALED: FlagSet
}
}Symbol collections and namespace management for lexical scoping.
trait Scopes { self: Universe =>
type Scope >: Null <: ScopeApi
type MemberScope >: Null <: MemberScopeApi with Scope
trait ScopeApi extends Iterable[Symbol] {
def lookup(name: Name): Symbol
def filter(p: Symbol => Boolean): Scope
def sorted: List[Symbol]
}
trait MemberScopeApi extends ScopeApi {
def nonPrivateMembers: Scope
}
}Source code position information for error reporting and tooling.
trait Positions { self: Universe =>
type Position >: Null <: PositionApi
trait PositionApi {
def line: Int
def column: Int
def start: Int
def end: Int
def source: scala.reflect.io.AbstractFile
def isDefined: Boolean
def isRange: Boolean
def show: String
}
}Abstract file system interface for compiler and reflection tooling.
package scala.reflect.io {
abstract class AbstractFile {
def name: String
def path: String
def container: AbstractFile
def isDirectory: Boolean
def lookupName(path: String, directory: Boolean): AbstractFile
def iterator: Iterator[AbstractFile]
def input: InputStream
def output: OutputStream
}
class PlainFile(file: File) extends AbstractFile
class VirtualFile(name: String, path: String) extends AbstractFile
class ZipArchive(file: File) extends AbstractFile
}Built-in Scala type definitions and standard names for core language constructs.
trait StandardDefinitions { self: Universe =>
val definitions: DefinitionsApi
trait DefinitionsApi {
def AnyClass: ClassSymbol
def AnyRefClass: ClassSymbol
def AnyValClass: ClassSymbol
def ObjectClass: ClassSymbol
def NothingClass: ClassSymbol
def NullClass: ClassSymbol
def StringClass: ClassSymbol
def IntClass: ClassSymbol
def BooleanClass: ClassSymbol
def ListClass: ClassSymbol
def OptionClass: ClassSymbol
def PredefModule: ModuleSymbol
}
}
trait StandardNames { self: Universe =>
val termNames: TermNamesApi
val typeNames: TypeNamesApi
trait TermNamesApi {
val CONSTRUCTOR: TermName
val apply: TermName
val update: TermName
val toString: TermName
val equals: TermName
val hashCode: TermName
}
trait TypeNamesApi {
val Any: TypeName
val AnyRef: TypeName
val AnyVal: TypeName
val Nothing: TypeName
val Null: TypeName
}
}