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.00
# Scala Reflection Library (scala-reflect)
1
2
Scala 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.
3
4
## Package Information
5
6
- **Package Name**: scala-reflect
7
- **Package Type**: maven
8
- **Language**: Scala
9
- **Coordinates**: `org.scala-lang:scala-reflect:2.13.16`
10
- **Installation**: `libraryDependencies += "org.scala-lang" % "scala-reflect" % "2.13.16"`
11
12
## Core Imports
13
14
```scala
15
import scala.reflect.runtime.universe._
16
import scala.reflect.runtime.{currentMirror => cm}
17
```
18
19
For macro development:
20
21
```scala
22
import scala.reflect.macros.blackbox.Context
23
// or for whitebox macros:
24
import scala.reflect.macros.whitebox.Context
25
```
26
27
## Basic Usage
28
29
```scala
30
import scala.reflect.runtime.universe._
31
import scala.reflect.runtime.{currentMirror => cm}
32
33
// Get type information
34
val tpe = typeOf[String]
35
println(s"Type: $tpe")
36
37
// Runtime reflection on instances
38
case class Person(name: String, age: Int)
39
val person = Person("Alice", 25)
40
41
// Get class mirror
42
val classMirror = cm.reflectClass(typeOf[Person].typeSymbol.asClass)
43
44
// Create new instance
45
val ctor = typeOf[Person].decl(termNames.CONSTRUCTOR).asMethod
46
val ctorMirror = classMirror.reflectConstructor(ctor)
47
val newPerson = ctorMirror("Bob", 30).asInstanceOf[Person]
48
49
// Field access
50
val instanceMirror = cm.reflect(person)
51
val nameFiled = typeOf[Person].decl(TermName("name")).asTerm
52
val fieldMirror = instanceMirror.reflectField(nameFiled)
53
println(s"Name: ${fieldMirror.get}")
54
55
// Method invocation
56
class Calculator {
57
def add(x: Int, y: Int): Int = x + y
58
}
59
60
val calc = new Calculator
61
val calcMirror = cm.reflect(calc)
62
val addMethod = typeOf[Calculator].decl(TermName("add")).asMethod
63
val methodMirror = calcMirror.reflectMethod(addMethod)
64
val result = methodMirror(2, 3)
65
println(s"Result: $result")
66
```
67
68
## Architecture
69
70
The Scala Reflection Library is organized around several key components:
71
72
- **Universe**: Central entry point providing the complete reflection API (`scala.reflect.api.Universe`)
73
- **Runtime Reflection**: JVM-specific implementation for runtime reflection (`scala.reflect.runtime.*`)
74
- **Compile-time Reflection**: Macro contexts for compile-time reflection (`scala.reflect.macros.*`)
75
- **Symbol System**: Representation of definitions, declarations, and scopes (`scala.reflect.api.Symbols`)
76
- **Type System**: Complete Scala type system representation (`scala.reflect.api.Types`)
77
- **AST Representation**: Abstract syntax tree manipulation (`scala.reflect.api.Trees`)
78
- **Mirror System**: Entry points for reflective operations (`scala.reflect.api.Mirrors`)
79
80
## Capabilities
81
82
### Runtime Reflection
83
84
Core runtime reflection functionality for inspecting types, creating instances, invoking methods, and accessing fields at runtime.
85
86
```scala { .api }
87
object universe extends scala.reflect.api.JavaUniverse
88
89
def runtimeMirror(classLoader: ClassLoader): RuntimeMirror
90
91
trait RuntimeMirror extends ReflectiveMirror {
92
def staticClass(fullName: String): ClassSymbol
93
def staticModule(fullName: String): ModuleSymbol
94
def reflect(obj: Any): InstanceMirror
95
}
96
```
97
98
[Runtime Reflection](./runtime-reflection.md)
99
100
### Type System
101
102
Comprehensive type system representation enabling type inspection, comparison, member lookup, and type transformations.
103
104
```scala { .api }
105
trait Types { self: Universe =>
106
type Type >: Null <: TypeApi
107
108
trait TypeApi { this: Type =>
109
def =:=(that: Type): Boolean
110
def <:<(that: Type): Boolean
111
def members: MemberScope
112
def member(name: Name): Symbol
113
def dealias: Type
114
def widen: Type
115
def erasure: Type
116
}
117
}
118
```
119
120
[Type System](./type-system.md)
121
122
### Symbol System
123
124
Symbol representation for all definitions including classes, methods, fields, and modules with complete metadata access.
125
126
```scala { .api }
127
trait Symbols { self: Universe =>
128
type Symbol >: Null <: SymbolApi
129
type TypeSymbol >: Null <: TypeSymbolApi with Symbol
130
type TermSymbol >: Null <: TermSymbolApi with Symbol
131
type MethodSymbol >: Null <: MethodSymbolApi with TermSymbol
132
type ClassSymbol >: Null <: ClassSymbolApi with TypeSymbol
133
type ModuleSymbol >: Null <: ModuleSymbolApi with TermSymbol
134
135
trait SymbolApi {
136
def name: Name
137
def info: Type
138
def owner: Symbol
139
def isPrivate: Boolean
140
def isProtected: Boolean
141
def isPublic: Boolean
142
}
143
}
144
```
145
146
[Symbol System](./symbol-system.md)
147
148
### Mirrors and Reflective Operations
149
150
Mirror system providing entry points for reflective operations including instance creation, method invocation, and field access.
151
152
```scala { .api }
153
trait Mirrors { self: Universe =>
154
type Mirror >: Null <: MirrorApi
155
type InstanceMirror >: Null <: InstanceMirrorApi
156
type MethodMirror >: Null <: MethodMirrorApi
157
type FieldMirror >: Null <: FieldMirrorApi
158
type ClassMirror >: Null <: ClassMirrorApi
159
type ModuleMirror >: Null <: ModuleMirrorApi
160
161
trait InstanceMirrorApi {
162
def reflectMethod(method: MethodSymbol): MethodMirror
163
def reflectField(field: TermSymbol): FieldMirror
164
}
165
166
trait MethodMirrorApi {
167
def apply(args: Any*): Any
168
}
169
}
170
```
171
172
[Mirrors and Reflective Operations](./mirrors-reflective-operations.md)
173
174
### Abstract Syntax Trees
175
176
AST representation and manipulation for compile-time and runtime tree processing, reification, and code generation.
177
178
```scala { .api }
179
trait Trees { self: Universe =>
180
type Tree >: Null <: TreeApi
181
182
trait TreeApi {
183
def pos: Position
184
def tpe: Type
185
def symbol: Symbol
186
def children: List[Tree]
187
def duplicate: Tree
188
}
189
190
def reify[T](expr: T): Expr[T]
191
}
192
```
193
194
[Abstract Syntax Trees](./abstract-syntax-trees.md)
195
196
### Type Tags and Type Information
197
198
Type tag system for preserving and accessing type information at runtime, enabling type-safe operations.
199
200
```scala { .api }
201
trait TypeTags { self: Universe =>
202
type TypeTag[T] >: Null <: WeakTypeTag[T]
203
type WeakTypeTag[T] >: Null <: WeakTypeTagApi[T]
204
205
trait WeakTypeTagApi[T] {
206
def tpe: Type
207
def in[U <: Universe with Singleton](otherMirror: scala.reflect.api.Mirror[U]): U#WeakTypeTag[T]
208
}
209
210
def typeOf[T: TypeTag]: Type
211
def weakTypeOf[T: WeakTypeTag]: Type
212
}
213
```
214
215
[Type Tags and Type Information](./type-tags-type-information.md)
216
217
### Macro Development
218
219
Compile-time reflection contexts for macro development including blackbox and whitebox macro support.
220
221
```scala { .api }
222
package scala.reflect.macros {
223
package blackbox {
224
trait Context extends scala.reflect.macros.Aliases
225
with scala.reflect.macros.Enclosures
226
with scala.reflect.macros.Names
227
with scala.reflect.macros.Reifiers
228
with scala.reflect.macros.Typers
229
with scala.reflect.macros.Universe {
230
val universe: Universe
231
val mirror: universe.Mirror
232
def prefix: Expr[_]
233
}
234
}
235
236
package whitebox {
237
trait Context extends blackbox.Context {
238
// Additional whitebox capabilities
239
}
240
}
241
}
242
```
243
244
[Macro Development](./macro-development.md)
245
246
### Expressions and Reification
247
248
Typed AST wrappers and reification system for converting between runtime values and compile-time AST representations.
249
250
```scala { .api }
251
trait Exprs { self: Universe =>
252
type Expr[+T] >: Null <: ExprApi[T]
253
254
trait ExprApi[+T] {
255
def tree: Tree
256
def staticType: Type
257
def actualType: Type
258
def splice: T
259
}
260
}
261
```
262
263
[Expressions and Reification](./expressions-reification.md)
264
265
## Additional APIs
266
267
### Annotations
268
269
Annotation support for both Java and Scala annotations on definitions and types.
270
271
```scala { .api }
272
trait Annotations { self: Universe =>
273
type Annotation >: Null <: AnyRef with AnnotationApi
274
275
val Annotation: AnnotationExtractor
276
277
abstract class AnnotationExtractor {
278
def apply(tree: Tree): Annotation
279
}
280
281
trait AnnotationApi {
282
def tree: Tree
283
}
284
}
285
```
286
287
### Liftables and Unliftables
288
289
Type classes for converting between Scala values and their AST representations.
290
291
```scala { .api }
292
trait Liftables { self: Universe =>
293
trait Liftable[T] {
294
def apply(value: T): Tree
295
}
296
297
object Liftable extends StandardLiftableInstances {
298
def apply[T](f: T => Tree): Liftable[T]
299
}
300
301
trait Unliftable[T] {
302
def unapply(tree: Tree): Option[T]
303
}
304
305
object Unliftable extends StandardUnliftableInstances {
306
def apply[T](pf: PartialFunction[Tree, T]): Unliftable[T]
307
}
308
}
309
```
310
311
### Quasiquotes
312
313
String interpolators for AST construction and pattern matching.
314
315
```scala { .api }
316
trait Quasiquotes { self: Universe =>
317
implicit class Quasiquote(ctx: StringContext) {
318
object q extends api // expressions and statements
319
object tq extends api // types
320
object cq extends api // case definitions
321
object pq extends api // patterns
322
object fq extends api // format strings
323
324
protected trait api {
325
def apply[A >: Any](args: A*): Tree
326
def unapply(scrutinee: Any): Any
327
}
328
}
329
}
330
```
331
332
### Printers
333
334
Pretty-printing support for reflection objects and ASTs.
335
336
```scala { .api }
337
trait Printers { self: Universe =>
338
trait TreePrinter {
339
def print(args: Any*): String
340
}
341
342
def show(any: Any): String
343
def showRaw(any: Any): String
344
}
345
```
346
347
### Internals
348
349
Low-level internal operations for advanced reflection use cases.
350
351
```scala { .api }
352
trait Internals { self: Universe =>
353
val internal: InternalApi
354
355
trait InternalApi {
356
def reificationSupport: ReificationSupportApi
357
def captureVariable(vble: Symbol): Unit
358
def referenceCapturedVariable(vble: Symbol): Tree
359
}
360
}
361
```
362
363
### Constants and Literals
364
365
Compile-time constant value representation and manipulation.
366
367
```scala { .api }
368
trait Constants { self: Universe =>
369
type Constant >: Null <: ConstantApi
370
371
trait ConstantApi {
372
def value: Any
373
def tpe: Type
374
def isNaN: Boolean
375
def convertTo(pt: Type): Constant
376
}
377
}
378
```
379
380
### Flag Sets and Modifiers
381
382
Symbol modifier flags for visibility, mutability, and other properties.
383
384
```scala { .api }
385
trait FlagSets { self: Universe =>
386
type FlagSet >: Null <: FlagSetApi
387
388
trait FlagSetApi {
389
def |(other: FlagSet): FlagSet
390
def &(other: FlagSet): FlagSet
391
def isEmpty: Boolean
392
}
393
394
val Flag: FlagValues
395
396
trait FlagValues {
397
val PRIVATE: FlagSet
398
val PROTECTED: FlagSet
399
val ABSTRACT: FlagSet
400
val FINAL: FlagSet
401
val IMPLICIT: FlagSet
402
val LAZY: FlagSet
403
val CASE: FlagSet
404
val SEALED: FlagSet
405
}
406
}
407
```
408
409
### Scopes and Namespaces
410
411
Symbol collections and namespace management for lexical scoping.
412
413
```scala { .api }
414
trait Scopes { self: Universe =>
415
type Scope >: Null <: ScopeApi
416
type MemberScope >: Null <: MemberScopeApi with Scope
417
418
trait ScopeApi extends Iterable[Symbol] {
419
def lookup(name: Name): Symbol
420
def filter(p: Symbol => Boolean): Scope
421
def sorted: List[Symbol]
422
}
423
424
trait MemberScopeApi extends ScopeApi {
425
def nonPrivateMembers: Scope
426
}
427
}
428
```
429
430
### Positions and Source Locations
431
432
Source code position information for error reporting and tooling.
433
434
```scala { .api }
435
trait Positions { self: Universe =>
436
type Position >: Null <: PositionApi
437
438
trait PositionApi {
439
def line: Int
440
def column: Int
441
def start: Int
442
def end: Int
443
def source: scala.reflect.io.AbstractFile
444
def isDefined: Boolean
445
def isRange: Boolean
446
def show: String
447
}
448
}
449
```
450
451
### File System Abstractions
452
453
Abstract file system interface for compiler and reflection tooling.
454
455
```scala { .api }
456
package scala.reflect.io {
457
abstract class AbstractFile {
458
def name: String
459
def path: String
460
def container: AbstractFile
461
def isDirectory: Boolean
462
def lookupName(path: String, directory: Boolean): AbstractFile
463
def iterator: Iterator[AbstractFile]
464
def input: InputStream
465
def output: OutputStream
466
}
467
468
class PlainFile(file: File) extends AbstractFile
469
class VirtualFile(name: String, path: String) extends AbstractFile
470
class ZipArchive(file: File) extends AbstractFile
471
}
472
```
473
474
### Standard Definitions and Names
475
476
Built-in Scala type definitions and standard names for core language constructs.
477
478
```scala { .api }
479
trait StandardDefinitions { self: Universe =>
480
val definitions: DefinitionsApi
481
482
trait DefinitionsApi {
483
def AnyClass: ClassSymbol
484
def AnyRefClass: ClassSymbol
485
def AnyValClass: ClassSymbol
486
def ObjectClass: ClassSymbol
487
def NothingClass: ClassSymbol
488
def NullClass: ClassSymbol
489
def StringClass: ClassSymbol
490
def IntClass: ClassSymbol
491
def BooleanClass: ClassSymbol
492
def ListClass: ClassSymbol
493
def OptionClass: ClassSymbol
494
def PredefModule: ModuleSymbol
495
}
496
}
497
498
trait StandardNames { self: Universe =>
499
val termNames: TermNamesApi
500
val typeNames: TypeNamesApi
501
502
trait TermNamesApi {
503
val CONSTRUCTOR: TermName
504
val apply: TermName
505
val update: TermName
506
val toString: TermName
507
val equals: TermName
508
val hashCode: TermName
509
}
510
511
trait TypeNamesApi {
512
val Any: TypeName
513
val AnyRef: TypeName
514
val AnyVal: TypeName
515
val Nothing: TypeName
516
val Null: TypeName
517
}
518
}
519
```