0
# Runtime Reflection
1
2
Core runtime reflection functionality for inspecting types, creating instances, invoking methods, and accessing fields at runtime using the JVM-based reflection system.
3
4
## Capabilities
5
6
### Runtime Universe
7
8
The main entry point for runtime reflection providing access to the complete reflection API.
9
10
```scala { .api }
11
/**
12
* Main runtime universe instance providing complete reflection capabilities
13
*/
14
lazy val universe: api.JavaUniverse
15
16
/**
17
* Create a runtime mirror bound to a specific classloader
18
* @param cl - ClassLoader to use for class loading
19
* @returns Mirror instance (JavaMirror)
20
*/
21
def runtimeMirror(cl: ClassLoader): Mirror
22
23
/**
24
* Runtime mirror corresponding to current lexical context (macro)
25
* Typically equivalent to universe.runtimeMirror(getClass.getClassLoader)
26
*/
27
def currentMirror: universe.Mirror
28
```
29
30
**Usage Example:**
31
32
```scala
33
import scala.reflect.runtime.universe._
34
import scala.reflect.runtime.{currentMirror => cm}
35
36
// Using default classloader
37
val mirror = runtimeMirror(getClass.getClassLoader)
38
39
// Using current mirror
40
val currentMirror = cm
41
```
42
43
### RuntimeMirror
44
45
Runtime mirror providing symbol lookup and reflection entry points.
46
47
```scala { .api }
48
/**
49
* JVM-specific runtime mirror for class loading and symbol resolution
50
*/
51
trait RuntimeMirror extends ReflectiveMirror {
52
/**
53
* Lookup a class by fully qualified name
54
* @param fullName - Fully qualified class name
55
* @returns ClassSymbol representing the class
56
*/
57
def staticClass(fullName: String): ClassSymbol
58
59
/**
60
* Lookup an object/module by fully qualified name
61
* @param fullName - Fully qualified object name
62
* @returns ModuleSymbol representing the object
63
*/
64
def staticModule(fullName: String): ModuleSymbol
65
66
/**
67
* Create an instance mirror for runtime reflection on objects
68
* @param obj - Object instance to reflect upon
69
* @returns InstanceMirror for the object
70
*/
71
def reflect(obj: Any): InstanceMirror
72
73
/**
74
* Create a class mirror for static operations and construction
75
* @param cls - ClassSymbol representing the class
76
* @returns ClassMirror for the class
77
*/
78
def reflectClass(cls: ClassSymbol): ClassMirror
79
80
/**
81
* Create a module mirror for singleton object access
82
* @param mod - ModuleSymbol representing the object
83
* @returns ModuleMirror for the object
84
*/
85
def reflectModule(mod: ModuleSymbol): ModuleMirror
86
87
/**
88
* Lookup a package by fully qualified name
89
* @param fullName - Fully qualified package name
90
* @returns ModuleSymbol representing the package
91
*/
92
def staticPackage(fullName: String): ModuleSymbol
93
}
94
```
95
96
**Usage Examples:**
97
98
```scala
99
import scala.reflect.runtime.universe._
100
import scala.reflect.runtime.{currentMirror => cm}
101
102
// Class lookup
103
val listClass = cm.staticClass("scala.collection.immutable.List")
104
val stringClass = cm.staticClass("java.lang.String")
105
106
// Object lookup
107
val listModule = cm.staticModule("scala.collection.immutable.List")
108
val predefModule = cm.staticModule("scala.Predef")
109
110
// Instance reflection
111
case class Person(name: String, age: Int)
112
val person = Person("Alice", 25)
113
val instanceMirror = cm.reflect(person)
114
115
// Class reflection
116
val personClass = cm.staticClass("Person")
117
val classMirror = cm.reflectClass(personClass)
118
```
119
120
### JavaMirror
121
122
JVM-specific runtime mirror implementation providing classloader integration.
123
124
```scala { .api }
125
/**
126
* JVM-specific mirror implementation extending RuntimeMirror
127
*/
128
trait JavaMirror extends scala.reflect.api.Mirror[universe.type] with RuntimeMirror {
129
/** The classloader used by this mirror */
130
val classLoader: ClassLoader
131
132
/** Convert a runtime class to a class symbol */
133
def classSymbol(rtcls: RuntimeClass): ClassSymbol
134
135
/** Convert a class symbol to a runtime class */
136
def runtimeClass(cls: ClassSymbol): RuntimeClass
137
138
/** Convert a module symbol to a runtime class */
139
def runtimeClass(mod: ModuleSymbol): RuntimeClass
140
}
141
```
142
143
### JavaUniverse
144
145
JVM-specific universe implementation extending the abstract Universe trait.
146
147
```scala { .api }
148
/**
149
* JVM-specific universe implementation providing runtime reflection
150
*/
151
trait JavaUniverse extends Universe
152
with RuntimeTypes
153
with RuntimeNames
154
with RuntimeSymbols
155
with RuntimeTrees
156
with RuntimeMirrors {
157
158
type RuntimeClass = java.lang.Class[_]
159
160
/**
161
* Default runtime mirror using current classloader
162
*/
163
lazy val runtimeMirror: RuntimeMirror
164
}
165
```
166
167
### Package Object Entry Points
168
169
Convenient entry points provided by the runtime package object.
170
171
```scala { .api }
172
/**
173
* Default runtime universe instance
174
*/
175
val universe: scala.reflect.runtime.JavaUniverse
176
177
/**
178
* Current mirror using thread context classloader
179
*/
180
def currentMirror: RuntimeMirror
181
```
182
183
**Usage Example:**
184
185
```scala
186
import scala.reflect.runtime.{universe => ru, currentMirror => cm}
187
188
// Type inspection
189
val stringType = ru.typeOf[String]
190
println(s"String type: $stringType")
191
192
// Symbol lookup using current mirror
193
val listSymbol = cm.staticClass("scala.collection.immutable.List")
194
```
195
196
## Complete Runtime Reflection Workflow
197
198
**Example: Complete reflection workflow for a case class**
199
200
```scala
201
import scala.reflect.runtime.universe._
202
import scala.reflect.runtime.{currentMirror => cm}
203
204
case class Product(name: String, price: Double, inStock: Boolean)
205
206
// 1. Get type information
207
val productType = typeOf[Product]
208
println(s"Product type: $productType")
209
210
// 2. Get class symbol and mirror
211
val productClass = productType.typeSymbol.asClass
212
val classMirror = cm.reflectClass(productClass)
213
214
// 3. Find constructor
215
val constructor = productType.decl(termNames.CONSTRUCTOR).asMethod
216
val constructorMirror = classMirror.reflectConstructor(constructor)
217
218
// 4. Create new instance
219
val newProduct = constructorMirror("Laptop", 999.99, true).asInstanceOf[Product]
220
println(s"Created: $newProduct")
221
222
// 5. Instance reflection
223
val instanceMirror = cm.reflect(newProduct)
224
225
// 6. Field access
226
val nameField = productType.decl(TermName("name")).asTerm
227
val fieldMirror = instanceMirror.reflectField(nameField)
228
println(s"Name field value: ${fieldMirror.get}")
229
230
// 7. Field modification (if var)
231
// fieldMirror.set("New Name")
232
233
// 8. Get all members
234
val members = productType.members
235
members.foreach { member =>
236
if (member.isTerm && !member.isMethod) {
237
println(s"Field: ${member.name} -> ${member.info}")
238
}
239
}
240
```
241
242
## Error Handling
243
244
Runtime reflection operations can throw various exceptions:
245
246
- `ScalaReflectionException` - General reflection errors
247
- `ClassNotFoundException` - When classes cannot be found
248
- `IllegalArgumentException` - Invalid method arguments
249
- `IllegalAccessException` - Access violations
250
251
**Example error handling:**
252
253
```scala
254
import scala.reflect.runtime.universe._
255
import scala.reflect.runtime.{currentMirror => cm}
256
import scala.util.{Try, Success, Failure}
257
258
def safeReflection[T](className: String): Try[ClassSymbol] = {
259
Try {
260
cm.staticClass(className)
261
}
262
}
263
264
safeReflection("com.example.NonExistentClass") match {
265
case Success(cls) => println(s"Found class: ${cls.name}")
266
case Failure(ex) => println(s"Reflection failed: ${ex.getMessage}")
267
}
268
```