CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlin--kotlin-reflect

Runtime component for full Kotlin reflection support, enabling inspection and manipulation of Kotlin classes, functions, properties, and types at runtime

Pending
Overview
Eval results
Files

class-introspection.mddocs/

Class Introspection

Enhanced class inspection capabilities including member enumeration, hierarchy traversal, constructor access, companion object handling, and instance operations for comprehensive class analysis.

Capabilities

Member Enumeration

Access all members of a class including functions, properties, and constructors with various filtering options.

/** All functions and properties declared in this class, excluding inherited */
val KClass<*>.declaredMembers: Collection<KCallable<*>>

/** All functions and properties including inherited from supertypes */
val KClass<*>.members: Collection<KCallable<*>>

/** All constructors of this class */
val <T : Any> KClass<T>.constructors: Collection<KFunction<T>>

/** Primary constructor of this class, or null if none */
val <T : Any> KClass<T>.primaryConstructor: KFunction<T>?

Usage Examples:

open class Parent {
    val parentProperty: String = "parent"
    fun parentMethod(): String = "parent"
}

class Child : Parent() {
    val childProperty: Int = 42
    fun childMethod(): Int = 42
    
    constructor() : super()
    constructor(value: Int) : super()
}

val childClass = Child::class

// Get all members (including inherited)
val allMembers = childClass.members
println("Total members: ${allMembers.size}")

// Get only declared members
val declaredMembers = childClass.declaredMembers
println("Declared members: ${declaredMembers.size}")

// Get constructors
val constructors = childClass.constructors
println("Constructors: ${constructors.size}")  // 2

val primaryConstructor = childClass.primaryConstructor
println("Has primary constructor: ${primaryConstructor != null}")

Function Access

Access functions with different visibility and extension patterns.

/** All functions including inherited and static */
val KClass<*>.functions: Collection<KFunction<*>>

/** Non-extension non-static functions declared in class and supertypes */
val KClass<*>.memberFunctions: Collection<KFunction<*>>

/** Extension functions declared in class and supertypes */
val KClass<*>.memberExtensionFunctions: Collection<KFunction<*>>

/** Static functions declared in this class */
val KClass<*>.staticFunctions: Collection<KFunction<*>>

/** All functions declared only in this class */
val KClass<*>.declaredFunctions: Collection<KFunction<*>>

/** Non-extension non-static functions declared only in this class */
val KClass<*>.declaredMemberFunctions: Collection<KFunction<*>>

/** Extension functions declared only in this class */
val KClass<*>.declaredMemberExtensionFunctions: Collection<KFunction<*>>

Usage Examples:

class MathUtils {
    fun add(a: Int, b: Int): Int = a + b
    
    companion object {
        @JvmStatic
        fun multiply(a: Int, b: Int): Int = a * b
    }
}

fun MathUtils.subtract(a: Int, b: Int): Int = a - b

val mathClass = MathUtils::class

// Get different types of functions
val allFunctions = mathClass.functions
val memberFunctions = mathClass.memberFunctions
val staticFunctions = mathClass.staticFunctions
val declaredFunctions = mathClass.declaredFunctions

println("All functions: ${allFunctions.size}")
println("Member functions: ${memberFunctions.size}")
println("Static functions: ${staticFunctions.size}")
println("Declared functions: ${declaredFunctions.size}")

// Find specific functions
val addFunction = memberFunctions.find { it.name == "add" }
val multiplyFunction = staticFunctions.find { it.name == "multiply" }

println("Found add function: ${addFunction != null}")
println("Found multiply function: ${multiplyFunction != null}")

Property Access

Access properties with different receiver patterns and mutability.

/** Non-extension properties declared in class and supertypes */
val <T : Any> KClass<T>.memberProperties: Collection<KProperty1<T, *>>

/** Extension properties declared in class and supertypes */
val <T : Any> KClass<T>.memberExtensionProperties: Collection<KProperty2<T, *, *>>

/** Static properties declared in this class */
val KClass<*>.staticProperties: Collection<KProperty0<*>>

/** Non-extension properties declared only in this class */
val <T : Any> KClass<T>.declaredMemberProperties: Collection<KProperty1<T, *>>

/** Extension properties declared only in this class */
val <T : Any> KClass<T>.declaredMemberExtensionProperties: Collection<KProperty2<T, *, *>>

Usage Examples:

class Person(val name: String) {
    var age: Int = 0
    
    companion object {
        const val SPECIES = "Homo sapiens"
    }
}

val Person.displayName: String
    get() = "Person: $name"

val personClass = Person::class

// Get different types of properties
val memberProperties = personClass.memberProperties
val staticProperties = personClass.staticProperties
val declaredProperties = personClass.declaredMemberProperties

memberProperties.forEach { property ->
    println("Property: ${property.name}, type: ${property.returnType}")
}
// Property: name, type: kotlin.String
// Property: age, type: kotlin.Int

staticProperties.forEach { property ->
    println("Static property: ${property.name}")
}
// Static property: SPECIES

// Check property mutability
val nameProperty = memberProperties.find { it.name == "name" }
val ageProperty = memberProperties.find { it.name == "age" }

println("name is mutable: ${nameProperty is KMutableProperty1<*, *>}")  // false
println("age is mutable: ${ageProperty is KMutableProperty1<*, *>}")    // true

Class Hierarchy

Navigate class inheritance hierarchies and inspect supertype relationships.

/** Immediate superclasses of this class in source order */
val KClass<*>.superclasses: List<KClass<*>>

/** Immediate supertypes of this class including type arguments */
val KClass<*>.supertypes: Collection<KType>

/** All superclasses including indirect ones in no particular order */
val KClass<*>.allSuperclasses: Collection<KClass<*>>

/** All supertypes including indirect ones */
val KClass<*>.allSupertypes: Collection<KType>

/** Returns true if this class is the same or subclass of base */
fun KClass<*>.isSubclassOf(base: KClass<*>): Boolean

/** Returns true if this class is the same or superclass of derived */
fun KClass<*>.isSuperclassOf(derived: KClass<*>): Boolean

Usage Examples:

interface Drawable {
    fun draw()
}

open class Shape : Drawable {
    override fun draw() {}
}

class Circle : Shape()

val circleClass = Circle::class
val shapeClass = Shape::class
val drawableClass = Drawable::class

// Inspect immediate hierarchy
val superclasses = circleClass.superclasses
println("Immediate superclasses: ${superclasses.map { it.simpleName }}")
// [Shape]

val supertypes = circleClass.supertypes
println("Immediate supertypes: ${supertypes.size}")  // 1

// Inspect complete hierarchy
val allSuperclasses = circleClass.allSuperclasses
println("All superclasses: ${allSuperclasses.map { it.simpleName }}")
// [Shape, Drawable, Any]

// Check relationships
println("Circle is subclass of Shape: ${circleClass.isSubclassOf(shapeClass)}")      // true
println("Circle is subclass of Drawable: ${circleClass.isSubclassOf(drawableClass)}")  // true
println("Shape is superclass of Circle: ${shapeClass.isSuperclassOf(circleClass)}")     // true

Companion Objects

Access companion objects and their instances.

/** Returns KClass representing the companion object, or null if none */
val KClass<*>.companionObject: KClass<*>?

/** Returns instance of the companion object, or null if none */
val KClass<*>.companionObjectInstance: Any?

Usage Examples:

class MyClass {
    companion object {
        const val CONSTANT = "value"
        fun companionFunction(): String = "companion"
    }
}

val myClass = MyClass::class

// Access companion object
val companionClass = myClass.companionObject
val companionInstance = myClass.companionObjectInstance

println("Has companion: ${companionClass != null}")  // true

if (companionClass != null && companionInstance != null) {
    // Get companion members
    val companionMembers = companionClass.memberFunctions
    val companionFunction = companionMembers.find { it.name == "companionFunction" }
    
    // Call companion function
    val result = companionFunction?.call(companionInstance)
    println("Companion function result: $result")  // "companion"
}

Instance Operations

Create instances and perform type casting operations.

/**
 * Creates a new instance using a constructor with no parameters 
 * or all optional parameters
 */
fun <T : Any> KClass<T>.createInstance(): T

/**
 * Casts the given value to this class type
 * Throws exception if value is not an instance
 */
fun <T : Any> KClass<T>.cast(value: Any?): T

/**
 * Safely casts the given value to this class type
 * Returns null if value is not an instance
 */
fun <T : Any> KClass<T>.safeCast(value: Any?): T?

Usage Examples:

class Person(val name: String = "Unknown", val age: Int = 0)

val personClass = Person::class

// Create instance using no-arg constructor
val person = personClass.createInstance()
println("Created person: ${person.name}, ${person.age}")  // "Unknown", 0

// Type casting
val anyValue: Any = Person("Alice", 25)
val stringValue: Any = "not a person"

// Safe casting
val castedPerson = personClass.safeCast(anyValue)
val failedCast = personClass.safeCast(stringValue)

println("Safe cast result: ${castedPerson?.name}")  // "Alice"
println("Failed cast result: $failedCast")          // null

// Exception throwing cast
try {
    val forceCast = personClass.cast(stringValue)
} catch (e: ClassCastException) {
    println("Cast failed: ${e.message}")
}

Type Information

Access detailed type information about classes including their generic type structure.

/** Returns type with star projections for all type parameters */
val KClassifier.starProjectedType: KType

/** Type parameters declared by this class */
val KClass<*>.typeParameters: List<KTypeParameter>

Usage Examples:

class GenericClass<T, U : Number> {
    fun method(param: T): U? = null
}

val genericClass = GenericClass::class

// Get type parameters
val typeParams = genericClass.typeParameters
println("Type parameters: ${typeParams.size}")  // 2

typeParams.forEachIndexed { index, param ->
    println("Parameter $index: ${param.name}, bounds: ${param.upperBounds}")
}
// Parameter 0: T, bounds: [kotlin.Any?]
// Parameter 1: U, bounds: [kotlin.Number]

// Get star projected type
val starProjectedType = genericClass.starProjectedType
println("Star projected type: $starProjectedType")  // GenericClass<*, *>

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-reflect

docs

callable-system.md

class-introspection.md

core-reflection.md

index.md

jvm-interoperability.md

type-system.md

tile.json