CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-scala-lang--scala-reflect

Reflection Library for the Scala Programming Language providing runtime reflection capabilities and metaprogramming support

Pending
Overview
Eval results
Files

runtime-reflection.mddocs/

Runtime Reflection

Core runtime reflection functionality for inspecting types, creating instances, invoking methods, and accessing fields at runtime using the JVM-based reflection system.

Capabilities

Runtime Universe

The main entry point for runtime reflection providing access to the complete reflection API.

/**
 * Main runtime universe instance providing complete reflection capabilities
 */
lazy val universe: api.JavaUniverse

/**
 * Create a runtime mirror bound to a specific classloader
 * @param cl - ClassLoader to use for class loading
 * @returns Mirror instance (JavaMirror)
 */
def runtimeMirror(cl: ClassLoader): Mirror

/**
 * Runtime mirror corresponding to current lexical context (macro)
 * Typically equivalent to universe.runtimeMirror(getClass.getClassLoader)
 */
def currentMirror: universe.Mirror

Usage Example:

import scala.reflect.runtime.universe._
import scala.reflect.runtime.{currentMirror => cm}

// Using default classloader
val mirror = runtimeMirror(getClass.getClassLoader)

// Using current mirror
val currentMirror = cm

RuntimeMirror

Runtime mirror providing symbol lookup and reflection entry points.

/**
 * JVM-specific runtime mirror for class loading and symbol resolution
 */
trait RuntimeMirror extends ReflectiveMirror {
  /** 
   * Lookup a class by fully qualified name
   * @param fullName - Fully qualified class name
   * @returns ClassSymbol representing the class
   */
  def staticClass(fullName: String): ClassSymbol
  
  /** 
   * Lookup an object/module by fully qualified name  
   * @param fullName - Fully qualified object name
   * @returns ModuleSymbol representing the object
   */
  def staticModule(fullName: String): ModuleSymbol
  
  /**
   * Create an instance mirror for runtime reflection on objects
   * @param obj - Object instance to reflect upon
   * @returns InstanceMirror for the object
   */
  def reflect(obj: Any): InstanceMirror
  
  /**
   * Create a class mirror for static operations and construction
   * @param cls - ClassSymbol representing the class
   * @returns ClassMirror for the class
   */
  def reflectClass(cls: ClassSymbol): ClassMirror
  
  /**
   * Create a module mirror for singleton object access
   * @param mod - ModuleSymbol representing the object
   * @returns ModuleMirror for the object
   */
  def reflectModule(mod: ModuleSymbol): ModuleMirror
  
  /**
   * Lookup a package by fully qualified name
   * @param fullName - Fully qualified package name
   * @returns ModuleSymbol representing the package
   */
  def staticPackage(fullName: String): ModuleSymbol
}

Usage Examples:

import scala.reflect.runtime.universe._
import scala.reflect.runtime.{currentMirror => cm}

// Class lookup
val listClass = cm.staticClass("scala.collection.immutable.List")
val stringClass = cm.staticClass("java.lang.String")

// Object lookup  
val listModule = cm.staticModule("scala.collection.immutable.List")
val predefModule = cm.staticModule("scala.Predef")

// Instance reflection
case class Person(name: String, age: Int)
val person = Person("Alice", 25)
val instanceMirror = cm.reflect(person)

// Class reflection
val personClass = cm.staticClass("Person")  
val classMirror = cm.reflectClass(personClass)

JavaMirror

JVM-specific runtime mirror implementation providing classloader integration.

/**
 * JVM-specific mirror implementation extending RuntimeMirror
 */
trait JavaMirror extends scala.reflect.api.Mirror[universe.type] with RuntimeMirror {
  /** The classloader used by this mirror */
  val classLoader: ClassLoader
  
  /** Convert a runtime class to a class symbol */
  def classSymbol(rtcls: RuntimeClass): ClassSymbol
  
  /** Convert a class symbol to a runtime class */
  def runtimeClass(cls: ClassSymbol): RuntimeClass
  
  /** Convert a module symbol to a runtime class */
  def runtimeClass(mod: ModuleSymbol): RuntimeClass
}

JavaUniverse

JVM-specific universe implementation extending the abstract Universe trait.

/**
 * JVM-specific universe implementation providing runtime reflection
 */
trait JavaUniverse extends Universe 
                      with RuntimeTypes
                      with RuntimeNames  
                      with RuntimeSymbols
                      with RuntimeTrees
                      with RuntimeMirrors {
  
  type RuntimeClass = java.lang.Class[_]
  
  /**
   * Default runtime mirror using current classloader
   */
  lazy val runtimeMirror: RuntimeMirror
}

Package Object Entry Points

Convenient entry points provided by the runtime package object.

/**
 * Default runtime universe instance
 */
val universe: scala.reflect.runtime.JavaUniverse

/**
 * Current mirror using thread context classloader
 */  
def currentMirror: RuntimeMirror

Usage Example:

import scala.reflect.runtime.{universe => ru, currentMirror => cm}

// Type inspection
val stringType = ru.typeOf[String]
println(s"String type: $stringType")

// Symbol lookup using current mirror
val listSymbol = cm.staticClass("scala.collection.immutable.List")

Complete Runtime Reflection Workflow

Example: Complete reflection workflow for a case class

import scala.reflect.runtime.universe._
import scala.reflect.runtime.{currentMirror => cm}

case class Product(name: String, price: Double, inStock: Boolean)

// 1. Get type information
val productType = typeOf[Product]
println(s"Product type: $productType")

// 2. Get class symbol and mirror
val productClass = productType.typeSymbol.asClass
val classMirror = cm.reflectClass(productClass)

// 3. Find constructor
val constructor = productType.decl(termNames.CONSTRUCTOR).asMethod
val constructorMirror = classMirror.reflectConstructor(constructor)

// 4. Create new instance
val newProduct = constructorMirror("Laptop", 999.99, true).asInstanceOf[Product]
println(s"Created: $newProduct")

// 5. Instance reflection
val instanceMirror = cm.reflect(newProduct)

// 6. Field access
val nameField = productType.decl(TermName("name")).asTerm
val fieldMirror = instanceMirror.reflectField(nameField)
println(s"Name field value: ${fieldMirror.get}")

// 7. Field modification (if var)
// fieldMirror.set("New Name")

// 8. Get all members
val members = productType.members
members.foreach { member =>
  if (member.isTerm && !member.isMethod) {
    println(s"Field: ${member.name} -> ${member.info}")
  }
}

Error Handling

Runtime reflection operations can throw various exceptions:

  • ScalaReflectionException - General reflection errors
  • ClassNotFoundException - When classes cannot be found
  • IllegalArgumentException - Invalid method arguments
  • IllegalAccessException - Access violations

Example error handling:

import scala.reflect.runtime.universe._
import scala.reflect.runtime.{currentMirror => cm}
import scala.util.{Try, Success, Failure}

def safeReflection[T](className: String): Try[ClassSymbol] = {
  Try {
    cm.staticClass(className)
  }
}

safeReflection("com.example.NonExistentClass") match {
  case Success(cls) => println(s"Found class: ${cls.name}")
  case Failure(ex) => println(s"Reflection failed: ${ex.getMessage}")
}

Install with Tessl CLI

npx tessl i tessl/maven-org-scala-lang--scala-reflect

docs

abstract-syntax-trees.md

expressions-reification.md

index.md

macro-development.md

mirrors-reflective-operations.md

runtime-reflection.md

symbol-system.md

type-system.md

type-tags-type-information.md

tile.json