### Java Class Example Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/config/migration.md A sample Java class used in reflection examples. ```java public class MyClass { private void myMethod(String content) { System.out.println("Hello " + content + "!"); } } ``` -------------------------------- ### Core API — `MemberScope.field {}` / `firstField {}` Source: https://context7.com/highcapable/kavaref/llms.txt This section details how to read and write fields, including private and static ones, using `FieldResolver`. It provides methods like `get()`, `set(value)`, and their `*Quietly` variants. ```APIDOC ## Core API — `MemberScope.field {}` / `firstField {}` ### Read and write fields, including private and static ones `FieldResolver` provides `get()` / `set(value)` and their `*Quietly` variants. ### Example: Read a private instance field ```kotlin // Read a private instance field val isRunning: Boolean? = test.asResolver() .firstField { name = "isTaskRunning" type = Boolean::class } .get() ``` ### Example: Write a private field ```kotlin // Write a private field test.asResolver() .firstField { name = "isTaskRunning" } .set(true) ``` ### Example: Read a static field ```kotlin // Read a static field (no instance needed — of(null) can be omitted) val tag: String? = Test::class.resolve() .firstField { name = "TAG" type = String::class modifiers(Modifiers.STATIC) } .get() ``` ### Example: Generic type filtering on a field ```kotlin // Generic type filtering on a field // class Wrapper { val data: List } Wrapper::class.resolve() .firstField { name = "data" genericType(List::class.parameterizedBy(String::class.toTypeMatcher())) } .of(wrapperInstance) .get>() ``` ### Example: Using `getQuietly` ```kotlin // getQuietly — returns null instead of throwing on failure val value = test.asResolver() .firstFieldOrNull { name = "maybeExists" } ?.getQuietly() ``` ``` -------------------------------- ### YukiReflection Field Acquisition Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/config/migration.md Demonstrates how to get a static field's value in YukiReflection. Note the chained calls including `.get()` and `.string()`. ```kotlin MyClass::class.java .field { name = "content" } // Return FieldFinder.Result .get() // Cannot be omitted, return FieldFinder.Result.Instance .string() // value ``` -------------------------------- ### Get Private Field Value using KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Shows how to retrieve the value of a private field (`isTaskRunning`) from an instance using KavaRef. It filters by field name and type and then uses `get()` to cast and retrieve the value. ```kotlin // Suppose this is an instance of this Class. val test: Test // Call and execute with KavaRef. val isTaskRunning = test.asResolver() .firstField { name = "isTaskRunning" type = Boolean::class }.get() ``` -------------------------------- ### KavaRef Field Acquisition Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/config/migration.md Shows how to get a static field's value using KavaRef. It uses `resolve()` and `firstField`, with `get()` directly retrieving the typed value. ```kotlin MyClass::class.resolve() .firstField { name = "content" } // Return FieldResolver .get() // value ``` -------------------------------- ### Read and write fields, including private and static ones Source: https://context7.com/highcapable/kavaref/llms.txt Use `firstField` or `field` to access fields by name, type, and modifiers. `get()` reads the field value, and `set(value)` writes to it. Use `*Quietly` variants for safe access. ```kotlin val isRunning: Boolean? = test.asResolver() .firstField { name = "isTaskRunning" type = Boolean::class } .get() ``` ```kotlin test.asResolver() .firstField { name = "isTaskRunning" } .set(true) ``` ```kotlin val tag: String? = Test::class.resolve() .firstField { name = "TAG" type = String::class modifiers(Modifiers.STATIC) } .get() ``` ```kotlin Wrapper::class.resolve() .firstField { name = "data" genericType(List::class.parameterizedBy(String::class.toTypeMatcher())) } .of(wrapperInstance) .get>() ``` ```kotlin val value = test.asResolver() .firstFieldOrNull { name = "maybeExists" } ?.getQuietly() ``` -------------------------------- ### Define Base Class for Reflection Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Defines a base class with a constructor and a private method. This serves as a foundational class for demonstrating reflection examples. ```java package com.demo; public class BaseTest { public BaseTest() { // ... } private void doBaseTask(String taskName) { // ... } } ``` -------------------------------- ### Create Instance via Private Constructor Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Demonstrates creating an instance of a class (`Test`) that has a private zero-argument constructor. It uses `resolve()`, `firstConstructor`, `emptyParameters()`, and `create()` to achieve this. ```kotlin val test = Test::class.resolve() .firstConstructor { // For the zero parameter constructor, // the following condition can be used to filter. // It is equivalent to parameterCount = 0. emptyParameters() }.create() // Create a new Test instance. ``` -------------------------------- ### Core API — `MemberScope.constructor {}` / `firstConstructor {}` Source: https://context7.com/highcapable/kavaref/llms.txt This section explains how to instantiate classes, including those with private constructors, using `ConstructorResolver`. It offers methods like `create()`, `createAsType()`, and their `*Quietly` variants. ```APIDOC ## Core API — `MemberScope.constructor {}` / `firstConstructor {}` ### Instantiate classes including those with private constructors `ConstructorResolver` provides `create(vararg args)`, `createAsType()`, and their `*Quietly` variants. ### Example: Private no-arg constructor ```kotlin // Private no-arg constructor → create instance val test: Test = Test::class.resolve() .firstConstructor { emptyParameters() } // equivalent to parameterCount = 0 .create() ``` ### Example: Cast created instance to a supertype ```kotlin // Cast created instance to a supertype val base: BaseTest = Test::class.resolve() .firstConstructor { emptyParameters() } .createAsType() ``` ### Example: Constructor with parameters ```kotlin // Constructor with parameters val obj: MyClass = MyClass::class.resolve() .firstConstructor { parameters(String::class, Int::class) } .create("hello", 42) ``` ### Example: Using `createQuietly` ```kotlin // createQuietly — returns null on failure val objOrNull = MyClass::class.resolve() .firstConstructorOrNull { emptyParameters() } ?.createQuietly() ``` ### Example: Using `createAsTypeQuietly` ```kotlin // createAsTypeQuietly — safe typed creation val safeBase = Test::class.resolve() .firstConstructor { emptyParameters() } .createAsTypeQuietly() ``` ``` -------------------------------- ### Configure kavaref-core with Version Catalog Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Add the kavaref-core dependency to your project's version catalog and build script. Replace `` with the actual version number. ```toml [versions] kavaref-core = "" [libraries] kavaref-core = { module = "com.highcapable.kavaref:kavaref-core", version.ref = "kavaref-core" } ``` ```kotlin implementation(libs.kavaref.core) ``` -------------------------------- ### Complete Manual Reflection Process in KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Implement the entire reflection process manually by creating MethodCondition and MemberCondition.Configuration. This offers maximum flexibility for complex reflection needs. ```kotlin // Suppose this is an example of this Class. val test: Test // Create MethodCondition manually. val condition = MethodCondition() condition.name = "doTask" condition.parameters(String::class) // Create MemberCondition.Configuration manually. val configuration = Test::class.java.createConfiguration( memberInstance = test, // Setting up instance. processorResolver = null, // Use the default resolver, refer to the "Custom Resolver" below. superclass = false, // Whether to filter in superclass. optional = MemberCondition.Configuration.Optional.NO // Configure optional conditions. ) // Create and start filtering. val resolvers = condition.build(configuration) // Get the first result. val resolver = resolvers.first() // Execute the method. resolver.invoke("task_name") ``` -------------------------------- ### Get Class Object Reference Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md Use the `classOf()` extension function as a concise alternative to `MyClass::class.java` for obtaining a `Class` object reference. ```kotlin val myClass = classOf() ``` -------------------------------- ### Configure kavaref-core with Traditional Method Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Add the kavaref-core dependency directly to your project's build script. Replace `` with the actual version number. ```kotlin implementation("com.highcapable.kavaref:kavaref-core:") ``` -------------------------------- ### Create New Class Instance with KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md Use `createInstance` to create a new instance of a class, handling constructor parameters automatically. Use `createInstanceOrNull` to return null on failure. Specify `isPublic = false` to access non-public constructors. Use `createInstanceAsType` to create an instance of a superclass. ```kotlin val myClass = MyClass::class.createInstance("Hello", 123) ``` ```kotlin val myClassOrNull = MyClass::class.createInstanceOrNull("Hello", 123) ``` ```kotlin val myClassWithPrivateConstructor = MyClass::class.createInstance("Private!", isPublic = false) ``` ```kotlin val mySuperClass = MyClass::class.createInstanceAsType("Hello", 123) ``` ```kotlin val mySuperClassOrNull = MyClass::class.createInstanceAsTypeOrNull("Hello", 123) ``` -------------------------------- ### Serialize Object to JSON using TypeRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md An example of an extension function `toJson()` that uses `TypeRef` to serialize an object to JSON with Gson, preserving generic types. ```kotlin val gson = Gson() inline fun T.toJson(): String = gson.toJson(this, typeRef().type) // Usage val json = listOf("KavaRef", "is", "awesome").toJson() ``` -------------------------------- ### Java Usage of KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Demonstrates how to use KavaRef from Java by resolving classes or objects and invoking methods. Note that KavaRef's API is Kotlin-centric. ```java public class Main { public static void main(String[] args) { // Suppose this is an example of this Class. Test test; // Call and execute with KavaRef. KavaRef.resolveClass(Test.class) .method() .name("doTask") .parameters(String.class) .build() .get(0) .of(test) .invoke("task_name"); // Or create KavaRef reflections using an instance. KavaRef.resolveObject(test) .method() .name("doTask") .parameters(String.class) .build() .get(0) .invoke("task_name"); } } ``` -------------------------------- ### Handling Non-Existent Methods in KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/config/migration.md Demonstrates how to handle cases where a method might not exist by using `.optional()` to prevent exceptions. It also shows the use of `firstMethodOrNull` as a safer alternative to `firstMethod` when dealing with potentially absent methods. ```kotlin val myClass: MyClass MyClass::class.resolve() .optional() .firstMethodOrNull { name = "doNonExistentMethod" parameters(String::class) }?.of(myClass)?.invoke("Hello, KavaRef!") ``` -------------------------------- ### Get Generic Superclass Type Arguments Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md Retrieve the generic type arguments of a class's superclass. Returns an empty array if retrieval fails or is not possible. ```kotlin val myClass: Class<*> val arguments = myClass.genericSuperclassTypeArguments() ``` -------------------------------- ### Instantiate Classes Dynamically with Kavaref Source: https://context7.com/highcapable/kavaref/llms.txt Allows creating class instances without explicit constructor signatures by matching argument types. Caches results for performance. ```kotlin import com.highcapable.kavaref.extension.* // Create public instance — types inferred from arguments val obj: MyClass = MyClass::class.createInstance("Hello", 123) // Null-safe version val objOrNull: MyClass? = MyClass::class.createInstanceOrNull("Hello", 123) // Include non-public constructors val priv: MyClass = MyClass::class.createInstance("Private!", isPublic = false) // Cast to supertype val base: BaseClass = MyClass::class.createInstanceAsType("Hello", 123) val baseOrNull: BaseClass? = MyClass::class.createInstanceAsTypeOrNull("Hello", 123) // Java Class variant val obj2: MyClass = MyClass::class.java.createInstance("Hello", 123) ``` -------------------------------- ### Entry Point: Create MemberScope with KavaRef.resolve() Source: https://context7.com/highcapable/kavaref/llms.txt Obtain a MemberScope by calling `.resolve()` on a KClass or Class reference, or `.asResolver()` on an instance. This scope is used to access methods, fields, and constructors. ```kotlin import com.highcapable.kavaref.KavaRef.Companion.resolve import com.highcapable.kavaref.KavaRef.Companion.asResolver // --- Target classes used throughout examples --- // class Test : BaseTest { // private constructor() // private val isTaskRunning: Boolean = false // private fun doTask(taskName: String) { ... } // private fun release(taskName: String, task: Function, finish: Boolean) { ... } // } val test: Test // assume this instance exists // 1. Reflect from KClass — no need to call .java Test::class.resolve() .firstMethod { name = "doTask"; parameters(String::class) } .of(test) .invoke("task_name") // 2. Reflect directly from an instance (instance is pre-bound) test.asResolver() .firstMethod { name = "doTask"; parameters(String::class) } .invoke("task_name") // of(test) not needed // 3. Java interop — use static helpers KavaRef.resolveClass / KavaRef.resolveObject KavaRef.resolveClass(Test::class.java) .method().name("doTask").parameters(String::class.java).build() .get(0).of(test).invoke("task_name") // 4. Class obtained dynamically (Class<*> → must cast to Class) val myClass = Class.forName("com.example.Test") as Class val instance: Any // the Test instance myClass.resolve() .firstMethod { name = "doTask" } .of(instance).invoke("task_name") ``` -------------------------------- ### Configure Repositories in build.gradle.kts Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/guide/quick-start.md Configure Maven repositories in your project's build.gradle.kts file. Includes Maven Central and an optional public repository for KavaRef dependencies. ```kotlin repositories { google() mavenCentral() // (Optional) You can add this URL to use our public repository // When Sonatype-OSS fails and cannot publish dependencies, this repository is added as a backup // For details, please visit: https://github.com/HighCapable/maven-repository maven("https://raw.githubusercontent.com/HighCapable/maven-repository/main/repository/releases") } ``` -------------------------------- ### KavaRef Method Invocation vs YukiReflection Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/config/migration.md Compares how to invoke a method using KavaRef and YukiReflection. KavaRef uses `resolve()` to create a reflection scope and `asResolver()` for instance-based reflection, while YukiReflection uses direct class/instance access. ```kotlin // Assume that's your MyClass instance. val myClass: MyClass // Call and execute using KavaRef. MyClass::class.resolve().firstMethod { name = "myMethod" parameters(String::class) }.of(myClass).invoke("Hello, KavaRef!") // Direct reference to instance. myClass.asResolver().firstMethod { name = "myMethod" parameters(String::class) }.invoke("Hello, KavaRef!") ``` ```kotlin // Assume that's your MyClass instance. val myClass: MyClass // Call and execute using YukiReflection. MyClass::class.java.method { name = "myMethod" param(StringClass) }.get(myClass).call("Hello, YukiReflection!") // Direct reference to instance. myClass.current().method { name = "myMethod" param(StringClass) }.call("Hello, YukiReflection!") ``` -------------------------------- ### Matching Generic Type Signatures Source: https://context7.com/highcapable/kavaref/llms.txt Demonstrates how to use `TypeMatcher` and its extensions to match generic type parameters, including type variables, parameterized types, and generic arrays. ```APIDOC ## Matching Generic Type Signatures `TypeMatcher` and its extension functions (`typeVar`, `toTypeMatcher`, `parameterizedBy`, `asGenericArray`) allow matching on generic parameter types that survive erasure. ```kotlin import com.highcapable.kavaref.condition.matcher.extension.* // class Box { fun print(item: T, str: String) { ... } } val box: Box box.asResolver() .firstMethod { name = "print" genericParameters( typeVar("T"), // matches the type variable "T" String::class.toTypeMatcher() // matches String ) } .invoke("item_value", "str_value") // Parameterized type: method taking List someObj.asResolver() .firstMethod { name = "process" genericParameters( List::class.parameterizedBy(String::class.toTypeMatcher()) ) } .invoke(listOf("a", "b")) // Generic array: method taking String[] someObj.asResolver() .firstMethod { name = "processArray" genericParameters( String::class.toTypeMatcher().asGenericArray() ) } .invoke(arrayOf("x")) ``` ``` -------------------------------- ### Create BaseTest Instance Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Use `resolve().firstConstructor().createAsType()` to create a new instance of a class with empty parameters. This method is useful for instantiating objects that do not require any arguments during construction. ```kotlin val test = Test::class.resolve() .firstConstructor { emptyParameters() }.createAsType() // Create a new BaseTest instance. ``` -------------------------------- ### Instantiate classes with private constructors Source: https://context7.com/highcapable/kavaref/llms.txt Use `firstConstructor` or `constructor` to find constructors by parameter types. `create()` instantiates the class. `createAsType()` casts the result. Use `*Quietly` variants for safe instantiation. ```kotlin val test: Test = Test::class.resolve() .firstConstructor { emptyParameters() } // equivalent to parameterCount = 0 .create() ``` ```kotlin val base: BaseTest = Test::class.resolve() .firstConstructor { emptyParameters() } .createAsType() ``` ```kotlin val obj: MyClass = MyClass::class.resolve() .firstConstructor { parameters(String::class, Int::class) } .create("hello", 42) ``` ```kotlin val objOrNull = MyClass::class.resolve() .firstConstructorOrNull { emptyParameters() } ?.createQuietly() ``` ```kotlin val safeBase = Test::class.resolve() .firstConstructor { emptyParameters() } .createAsTypeQuietly() ``` -------------------------------- ### Add KavaRef Extension Dependency using Version Catalog Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md Configure the KavaRef extension dependency in your project's `gradle/libs.versions.toml` file. Replace `` with the actual version number. ```toml [versions] kavaref-extension = "" [libraries] kavaref-extension = { module = "com.highcapable.kavaref:kavaref-extension", version.ref = "kavaref-extension" } ``` -------------------------------- ### Resolving Members from KClass or Class Source: https://context7.com/highcapable/kavaref/llms.txt Demonstrates how to obtain a `MemberScope` using `.resolve()` on a `KClass` or `Class` reference, and how to use `.asResolver()` on an instance for direct reflection. ```APIDOC ## Entry point: create a `MemberScope` from a class reference Call `.resolve()` on any `KClass` or `Class` (or `.asResolver()` on an instance) to open a reflection scope. From there use `method {}`, `field {}`, or `constructor {}` builders to filter and obtain resolvers. ```kotlin import com.highcapable.kavaref.KavaRef.Companion.resolve import com.highcapable.kavaref.KavaRef.Companion.asResolver // --- Target classes used throughout examples --- // class Test : BaseTest { // private constructor() // private val isTaskRunning: Boolean = false // private fun doTask(taskName: String) { ... } // private fun release(taskName: String, task: Function, finish: Boolean) { ... } // } val test: Test // assume this instance exists // 1. Reflect from KClass — no need to call .java Test::class.resolve() .firstMethod { name = "doTask"; parameters(String::class) } .of(test) .invoke("task_name") // 2. Reflect directly from an instance (instance is pre-bound) test.asResolver() .firstMethod { name = "doTask"; parameters(String::class) } .invoke("task_name") // of(test) not needed // 3. Java interop — use static helpers KavaRef.resolveClass / KavaRef.resolveObject KavaRef.resolveClass(Test::class.java) .method().name("doTask").parameters(String::class.java).build() .get(0).of(test).invoke("task_name") // 4. Class obtained dynamically (Class<*> → must cast to Class) val myClass = Class.forName("com.example.Test") as Class val instance: Any // the Test instance myClass.resolve() .firstMethod { name = "doTask" } .of(instance).invoke("task_name") ``` ``` -------------------------------- ### Invoking Methods with KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/config/migration.md Shows how to resolve a method by name and parameters, then invoke it on a specific instance with provided arguments. Type safety is enforced when passing the instance to 'of()'. ```kotlin // Assume that's your MyClass instance. val myClass: MyClass // Using KavaRef to call and execute. MyClass::class.resolve() .firstMethod { name = "myMethod" parameters(String::class) } // Only instances of type MyClass can be passed in. .of(myClass) .invoke("Hello, KavaRef!") ``` -------------------------------- ### Call Reflection APIs to Access Java Class Members Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/about/future.md Demonstrates how to use KavaRef's existing API to reflectively access fields and methods of a Java class. This shows the current approach before automatic code generation. ```kotlin MyClass().resolve().apply { // Call myField. val value = firstField { name = "myField" }.get() // Call myMethod1. val methodValue = firstMethod { name = "myMethod1" }.invoke("test", 0) // Call myMethod2. firstMethod { name = "myMethod2" }.invoke() // Call myMethod3. firstMethod { name = "myMethod3" }.invoke("test") } ``` -------------------------------- ### Create Java Array Classes Concisely Source: https://context7.com/highcapable/kavaref/llms.txt Provides a concise way to create `Class` objects for Java array types using `ArrayClass()`. Supports various input types for flexibility. ```kotlin import com.highcapable.kavaref.extension.* // Equivalent to: java.lang.reflect.Array.newInstance(String::class.java, 0).javaClass val stringArrayClass: Class = ArrayClass(String::class) // From Java Class val intArrayClass: Class = ArrayClass(Int::class.java) // From string class name val dynamicArrayClass: Class = ArrayClass("com.example.MyClass") val dynamicWithLoader: Class = ArrayClass("com.example.MyClass", myClassLoader) // Use in reflection conditions Test::class.resolve() .firstMethod { name = "processStrings" parameters(ArrayClass(String::class)) } .of(test) .invoke(arrayOf("a", "b", "c")) ``` -------------------------------- ### Custom Log Implementation Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Implement the `KavaRefRuntime.Logger` interface to create a custom logger. Specify a tag for log messages and implement methods for different log levels. ```kotlin class MyLogger : KavaRefRuntime.Logger { // Here you can specify the tag for log printing. override val tag = "MyLogger" override fun debug(msg: Any?, throwable: Throwable?) { // Implement your log printing logic here. } override fun info(msg: Any?, throwable: Throwable?) { // Implement your log printing logic here. } override fun warn(msg: Any?, throwable: Throwable?) { // Implement your log printing logic here. } override fun error(msg: Any?, throwable: Throwable?) { // Implement your log printing logic here. } } ``` -------------------------------- ### Configure Java Version for Java Project Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/guide/quick-start.md Set the Java source and target compatibility to version 17 for a Java project using Kotlin DSL. ```kotlin java { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } kotlin { jvmToolchain(17) } ``` -------------------------------- ### Invoke Private Method using KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Demonstrates how to invoke a private method (`doTask`) on an instance of the `Test` class using KavaRef. It shows filtering by method name and parameter type. ```kotlin // Suppose this is an instance of this Class. val test: Test // Reflect it by instantiating Class. // In KavaRef you don't need to convert it to `java.lang.Class`, // it will automatically call KClass.java. Test::class // Create KavaRef reflections. .resolve() // Create method condition. .method { // Set method name. name = "doTask" // Set method parameter type. parameters(String::class) } // After the condition is executed, the matching List // instance will be returned. // Here we get the first filtering result. .first() // Set an instance of Test on MethodResolver. .of(test) // Call the method and pass in parameters. .invoke("task_name") ``` -------------------------------- ### Define a Java Class Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/index.md This Java class defines a simple method for demonstration purposes. ```java public class World { private void sayHello(String content) { System.out.println("Hello " + content + "!"); } } ``` -------------------------------- ### Invoke Private Method using Instance Resolver Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Demonstrates invoking a private method by first obtaining a KavaRef resolver from an existing instance of the class. This avoids the need for `of(test)` as the instance is already associated. ```kotlin // Here, the test instance test will be passed to // KavaRef and get test::class.java. test.asResolver() .firstMethod { name = "doTask" parameters(String::class) } // Since you set up an instance, of(test) is no longer needed here. .invoke("task_name") ``` -------------------------------- ### Add KavaRef Extension Dependency using Traditional Method Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md Configure the KavaRef extension dependency directly in your `build.gradle.kts` file. Replace `` with the actual version number. ```kotlin implementation("com.highcapable.kavaref:kavaref-extension:") ``` -------------------------------- ### Create Array Class Object with KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md KavaRef simplifies the creation of array `Class` objects using `ArrayClass`. This is a more concise alternative to using `java.lang.reflect.Array.newInstance().javaClass`. ```kotlin val arrayClass = ArrayClass(String::class) ``` -------------------------------- ### Class Loading from Strings Source: https://context7.com/highcapable/kavaref/llms.txt Load `Class` objects from strings using `toClass()`, with support for fallback names and lazy loading via `VariousClass` and `lazyClass`. ```APIDOC ## Extension API — `String.toClass()` / `VariousClass` / `lazyClass` ### Load `Class` objects from strings, with fallback names and lazy loading `kavaref-extension` provides safe class loading helpers including a global `ClassLoaderProvider`. ```kotlin import com.highcapable.kavaref.extension.* // String → Class (throws if not found) val cls: Class = "com.example.MyClass".toClass() // String → typed Class val cls2: Class = "com.example.MyClass".toClass() // Null-safe val clsOrNull: Class? = "com.example.MyClass".toClassOrNull() // Set a global ClassLoader (e.g., Android's app classloader) ClassLoaderProvider.classLoader = context.classLoader // Load with explicit loader val cls3 = "com.example.MyClass".toClass(myCustomClassLoader) // VariousClass: try multiple names (for obfuscated code) val obfClass = VariousClass("com.example.a", "com.example.b").load() val obfOrNull = VariousClass("com.example.a", "com.example.b").loadOrNull() // Lazy loading — only resolved on first access val myClass: Class by lazyClass("com.example.MyClass") val optionalClass: Class? by lazyClassOrNull("com.example.MaybeExists") val variousLazy: Class? by lazyClassOrNull(VariousClass("com.example.a", "com.example.b")) // Use after lazy resolution myClass.resolve().firstMethod { name = "run" }.invoke() ``` ``` -------------------------------- ### Implement KavaRef Extension Dependency in build.gradle.kts Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md Include the KavaRef extension dependency in your `build.gradle.kts` file using the version catalog. ```kotlin implementation(libs.kavaref.extension) ``` -------------------------------- ### Create Class Object with Specific ClassLoader Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md Manually pass a `ClassLoader` instance to the `toClass()` method to specify which `ClassLoader` to use for loading the class. ```kotlin val myClass = "com.example.MyClass".toClass(customClassLoader) ``` -------------------------------- ### Advanced Manual Usage and Condition Reuse Source: https://context7.com/highcapable/kavaref/llms.txt Covers building and reusing `MethodCondition` objects manually, merging conditions, and caching resolvers using `lazy` for efficiency. ```APIDOC ## Build and reuse `MethodCondition` objects manually; merge conditions Conditions can be created manually for multiplexing across multiple reflection calls. The builder chain style is also available for Java interoperability. ```kotlin // Manual builder chain (useful from Java or when avoiding lambdas) Test::class.resolve() .method() .name("doTask") .parameters(String::class) .build() .first() .of(test) .invoke("task_name") // Reusable MethodCondition val condition = MethodCondition() condition.name = "doTask" condition.parameters(String::class) Test::class.resolve().firstMethod(condition).of(test).invoke("task_name") // Merging two conditions (condition2 overwrites non-null fields in condition1) val c1 = MethodCondition().apply { name = "doTask" } val c2 = MethodCondition().apply { parameters(String::class) } c1 mergeWith c2 // c1 now has both name and parameters Test::class.resolve().firstMethod(c1).of(test).invoke("task_name") // Caching with lazy + copy() to avoid duplicate-instance errors val cachedResolver by lazy { Test::class.resolve().firstMethod { name = "doTask"; parameters(String::class) } } // Always copy before setting a new instance cachedResolver.copy().of(test).invoke("task_name") // Full manual pipeline with MemberCondition.Configuration val cfg = Test::class.java.createConfiguration(memberInstance = test) val resolvers: List> = condition.build(cfg) resolvers.first().invoke("task_name") ``` ``` -------------------------------- ### Invoke Private Method Directly using KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md A simplified way to invoke a private method using KavaRef's `firstMethod` shortcut. This method directly returns the first matching `MethodResolver`. ```kotlin Test::class .resolve() // Use firstMethod directly to get the first matching // MethodResolver instance. .firstMethod { name = "doTask" parameters(String::class) } .of(test) .invoke("task_name") ``` -------------------------------- ### Load Class Objects Safely from Strings Source: https://context7.com/highcapable/kavaref/llms.txt Use extension functions like `toClass()`, `toClassOrNull()`, `VariousClass`, and `lazyClass` for robust class loading from string names. Supports fallback names and lazy initialization, with an option to set a global ClassLoaderProvider. ```kotlin import com.highcapable.kavaref.extension.* // String → Class (throws if not found) val cls: Class = "com.example.MyClass".toClass() // String → typed Class val cls2: Class = "com.example.MyClass".toClass() // Null-safe val clsOrNull: Class? = "com.example.MyClass".toClassOrNull() // Set a global ClassLoader (e.g., Android's app classloader) ClassLoaderProvider.classLoader = context.classLoader // Load with explicit loader val cls3 = "com.example.MyClass".toClass(myCustomClassLoader) // VariousClass: try multiple names (for obfuscated code) val obfClass = VariousClass("com.example.a", "com.example.b").load() val obfOrNull = VariousClass("com.example.a", "com.example.b").loadOrNull() // Lazy loading — only resolved on first access val myClass: Class by lazyClass("com.example.MyClass") val optionalClass: Class? by lazyClassOrNull("com.example.MaybeExists") val variousLazy: Class? by lazyClassOrNull(VariousClass("com.example.a", "com.example.b")) // Use after lazy resolution myClass.resolve().firstMethod { name = "run" }.invoke() ``` -------------------------------- ### Gradle Dependency Configuration for KavaRef Source: https://context7.com/highcapable/kavaref/llms.txt Configure Maven repositories and declare kavaref-core and kavaref-extension as dependencies in your Gradle build files. Ensure Java and Kotlin toolchains are set to version 17 or higher. ```kotlin // settings.gradle.kts / build.gradle.kts - repositories repositories { mavenCentral() // optional backup repository maven("https://raw.githubusercontent.com/HighCapable/maven-repository/main/repository/releases") } // build.gradle.kts - Java/Kotlin version java { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } kotlin { jvmToolchain(17) } // build.gradle.kts - dependencies dependencies { implementation("com.highcapable.kavaref:kavaref-core:1.0.2") implementation("com.highcapable.kavaref:kavaref-extension:1.0.2") } // gradle/libs.versions.toml (Version Catalog alternative) // [versions] // kavaref = "1.0.2" // [libraries] // kavaref-core = { module = "com.highcapable.kavaref:kavaref-core", version.ref = "kavaref" } // kavaref-extension = { module = "com.highcapable.kavaref:kavaref-extension", version.ref = "kavaref" } ``` -------------------------------- ### Filter and invoke methods with typed conditions Source: https://context7.com/highcapable/kavaref/llms.txt Use `firstMethod` or `method` to find methods by name, parameter types, and return types. `invoke` executes the method with provided arguments. Use `invokeQuietly` to suppress exceptions. ```kotlin test.asResolver() .firstMethod { name = "doTask" parameters(String::class) } .invoke("hello") ``` ```kotlin Test::class.resolve() .firstMethod { name = "getName" returnType = String::class // or lambda: returnType { it == String::class.java } } .of(test) .invoke() // typed invocation returns String? ``` ```kotlin Test::class.resolve() .firstMethod { name = "release" parameters(String::class, VagueType, Boolean::class) } .of(test) .invoke("taskName", someFunctionRef, true) ``` ```kotlin Test::class.resolve() .firstMethod { name { it.equals("dotask", ignoreCase = true) } parameters(String::class) } .of(test).invoke("task_name") ``` ```kotlin Test::class.resolve() .firstField { name = "TAG" type = String::class modifiers(Modifiers.STATIC) } .get() // returns "Test" (the static value) ``` ```kotlin val allMethods: List> = Test::class.resolve() .method { parameters(String::class) } // iterate or use .map { it.of(test).invoke("arg") } ``` ```kotlin test.asResolver() .firstMethodOrNull { name = "maybeExists" } ?.invokeQuietly("arg") ``` -------------------------------- ### ClassLoader Extensions for Class Loading Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md KavaRef provides extensions for `ClassLoader` to simplify class loading. `loadClassOrNull` attempts to load a class and returns null if it fails. `hasClass` checks for the existence of a class within the `ClassLoader`. ```kotlin val myClassOrNull = classLoader.loadClassOrNull("com.example.MyClass") ``` ```kotlin val isClassExists = classLoader.hasClass("com.example.MyClass") ``` -------------------------------- ### Directly Call Kotlin Class with Reflection Annotations Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/about/future.md Shows how to directly call the Kotlin class defined with reflection annotations. The KavaRef API handles the underlying reflection code generation and execution. ```kotlin MyClass().also { // Call myField val value = it.myField // Call myMethod1 val methodValue = it.myMethod1("test", 0) // Call myMethod2 it.myMethod2() // Call myMethod3 it.myMethod3("test") } ``` -------------------------------- ### Core API — Generic Type Matchers (`TypeMatcher`) Source: https://context7.com/highcapable/kavaref/llms.txt This section introduces the concept of Generic Type Matchers used within KavaRef for precise type filtering, especially when dealing with generic types. ```APIDOC ## Core API — Generic Type Matchers (`TypeMatcher`) This section is intended to cover the usage of `TypeMatcher` for generic type filtering. (Further details would be provided here if available in the source). ``` -------------------------------- ### Optional Mode and Exception Handling Source: https://context7.com/highcapable/kavaref/llms.txt Explains how to use `.optional()` to suppress `NoSuchMethodException` or `NoSuchFieldException`, returning an empty list instead. `silent = true` can also suppress logging. ```APIDOC ## Suppress or silence `NoSuchMethodException` / `NoSuchFieldException` By default KavaRef throws immediately when no member matches. Calling `.optional()` on the scope suppresses the exception and returns an empty list (printing a WARN log). Use `.optional(silent = true)` to suppress logging too. ```kotlin // Default behavior — throws NoSuchMethodException with a formatted table: // +------------------------------+ // | class com.demo.Test | // +------------------+-----------+ // | name | missing | // +------------------+-----------+ Test::class.resolve() .method { name = "missing" } // throws here // optional() — returns empty list, prints WARN Test::class.resolve() .optional() .method { name = "missing" } // empty List // With optional(), always use *OrNull to avoid NoSuchElementException on empty list Test::class.resolve() .optional() .firstMethodOrNull { name = "missing" parameters(String::class) } ?.of(test) ?.invoke("arg") // Silent optional — no logs, no exceptions Test::class.resolve() .optional(silent = true) .firstMethodOrNull { name = "missing" } // null silently ``` ``` -------------------------------- ### Lazy Initialization of MemberResolver for Caching Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Use `lazy` delegate for caching `MemberResolver` instances. Be aware that cached instances cannot be modified and must be copied for subsequent calls that require new instances. ```kotlin val myResolver by lazy { Test::class.resolve() .firstMethod { name = "doTask" parameters(String::class) } } ``` ```kotlin // Suppose this is an instance of this Class. val test: Test // Call and execute using KavaRef. myResolver.copy().of(test).invoke("task_name") ``` -------------------------------- ### Create Class Object from String Name Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md Use the `toClass()` extension function to create a `Class` object from its fully qualified name. Use `toClassOrNull()` to return null if the class is not found instead of throwing an exception. ```kotlin val myClass = "com.example.MyClass".toClass() // You can use a method with OrNull suffix to return null // when the Class is not found instead of throwing an exception. val myClassOrNull = "com.example.MyClass".toClassOrNull() ``` -------------------------------- ### Accessing Class Fields with KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/config/migration.md Demonstrates how to resolve and access a specific field ('content') of a class using KavaRef. The 'of(null)' call is optional when working with static instances. ```kotlin MyClass::class.resolve() .firstField { name = "content" } // It's already a call chain object FieldResolver .of(null) // Can be omitted and return to the call chain object FieldResolver .get() // value ``` -------------------------------- ### Lazy Load Class Object with KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-extension.md Use `lazyClass` and `lazyClassOrNull` for lazy initialization of `Class` objects. This allows loading classes only when needed, which is useful for classes that depend on runtime conditions. `lazyClassOrNull` returns null if the class cannot be loaded. The `resolve()` method triggers the actual class loading. ```kotlin val myClass by lazyClass("com.example.MyClass") ``` ```kotlin val myClassOrNull by lazyClassOrNull("com.example.MyClass") ``` ```kotlin val otherClassOrNull by lazyClassOrNull(VariousClass("com.example.a", "com.example.b")) ``` ```kotlin myClass.resolve() ``` ```kotlin myClassOrNull?.resolve() ``` ```kotlin otherClassOrNull?.resolve() ``` -------------------------------- ### Manual MethodCondition Creation in KavaRef Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Manually create a MethodCondition to define specific filtering criteria for method reflection. This provides more control over the reflection process. ```kotlin // Suppose this is an example of this Class. val test: Test // Create MethodCondition manually. val condition = MethodCondition() condition.name = "doTask" condition.parameters(String::class) // Apply condition to reflection object. Test::class.resolve() .firstMethod(condition) .of(test) // Setting up instance. .invoke("task_name") ``` -------------------------------- ### Handle Missing Members Optionally Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md Use `optional()` to prevent exceptions when a member is not found. This will return an empty list instead of throwing an exception. ```kotlin Test::class.resolve() // Set optional conditions. .optional() .method { name = "doNonExistentMethod" } // Return empty List. ``` -------------------------------- ### Kotlin Class References and Hierarchy Checks Source: https://context7.com/highcapable/kavaref/llms.txt Provides shorthand for Java class retrieval and checks for subclass relationships and class modifiers. Useful for runtime class inspection. ```kotlin import com.highcapable.kavaref.extension.* // classOf() — shorthand for SomeClass::class.java (handles primitive unboxing) val stringClass: Class = classOf() val intPrimitive: Class = classOf() // int.class val intObject: Class = classOf(primitiveType = false) // Integer.class // Subclass check val isChild = MyClass::class isSubclassOf BaseClass::class // true if MyClass extends BaseClass val isNotChild = MyClass::class isNotSubclassOf OtherClass::class // Also works with mixed Class / KClass val yes: Boolean = MyClass::class isSubclassOf BaseClass::class.java // Hierarchy helpers val hasSuperclass: Boolean = MyClass::class.hasSuperclass // false if only extends Any val hasInterfaces: Boolean = MyClass::class.hasInterfaces // Modifier properties on Class val cls = classOf() println(cls.isPublic) // true println(cls.isFinal) // false println(cls.isAbstract) // false // ClassLoader extensions val loader: ClassLoader = Thread.currentThread().contextClassLoader val loadedCls: Class? = loader.loadClassOrNull("com.example.X") val exists: Boolean = loader.hasClass("com.example.X") ``` -------------------------------- ### Set Custom Logger Source: https://github.com/highcapable/kavaref/blob/main/docs-source/src/en/library/kavaref-core.md After implementing a custom logger, set it for KavaRef using `KavaRef.setLogger()`. ```kotlin KavaRef.setLogger(MyLogger()) ```