https://kotlinlang.org logo
Join SlackCommunities
Powered by
# reflect
  • e

    enighma

    04/18/2023, 5:10 PM
    I solved ^ by using .javaclass, but is there a kotlin idiomatic way to do the same? I was using a
    @JvmField
    annotation, so maybe that's what makes the above not work?
  • e

    Emil Kantis

    04/27/2023, 10:21 PM
    Is there any way to reflectively invoke a
    KCallable
    with default parameters, without explicitly supplying those parameters?
    • 1
    • 1
  • d

    dewildte

    08/25/2023, 8:02 PM
    Hi folks! New to using reflection APIs. I was wondering what the performance impact would be for
    ::functionReference.name
    ? More details in the 🧵
    ✔️ 1
    e
    s
    • 3
    • 4
  • s

    Settingdust

    09/10/2023, 3:14 AM
    How can I shadow and relocate reflect correctly? I tried relocating the kotlin to kotlin1910. But makes kotlin reflect can't find
    kotlin1910.kotlin1910_builtins
    . Then, I added custom transformers for avoiding
    shadow
    relocate the
    .kotlin_builtins
    constant in kotlin reflect. And relocate the
    kotlin/kotlin.kotlin_builtins
    to
    kotlin1910/kotlin1910.kotlin_builtins
    But the reflect can't find the builtin class
    AssertionError: Built-in class kotlin1910.Any is not found
    ✅ 1
    u
    • 2
    • 3
  • z

    Zoltan Demant

    10/10/2023, 6:09 AM
    I would like to remove the type property on this interface and instead figure it out at runtime. Is this possible using reflection, and if so: how?
    Copy code
    interface Dispatcher<T : Request<R>, R> {
    
        val type: KClass<T>
    
        suspend fun dispatch(
            request: T,
        ): R
    }
    e
    • 2
    • 14
  • n

    nikolaymetchev

    11/23/2023, 4:29 PM
    Is there an easy way to check if a method in a subclass overrides a method from an interface using the Kotlin reflection API? In particular if the interface is Java and uses Generics.
  • v

    v79

    11/23/2023, 8:43 PM
    To get a list of all the constructor properties of a Class, I either need reflection (with kotlin-reflect), or do it at compile time with Kapt or KSP. Is that right? I have a KType and I'd like to know its constructor properties - at runtime I've got
    (kType.classifier as KClass<*>).constructors
    and that requires kotlin-reflect. Any alternatives?
    ✅ 1
  • m

    martmists

    12/24/2023, 4:13 PM
    Does kotlin reflection provide a way to obtain the docstring used for a class/property?
    🚫 1
  • s

    Sean Proctor

    02/26/2024, 11:49 PM
    There's something pretty weird in the behavior of reflect. I have a value class wrapping a UUID (which while investigating this, I've realized might be a bit pointless). I have a data class containing that value class, and upon reflection, it is not null, when in fact it is null. If the same class is a normal class instead, in reflection it's null as expected. Is this a bug in reflect or am I just crazy for using a value class in this way?
    n
    • 2
    • 3
  • c

    Colton Idle

    03/09/2024, 7:01 AM
    Hello. Reflection noob but I'm basically trying to change the value of a static field in a java class. Here's the java class: https://github.com/tink-crypto/tink-java/blob/main/src/main/java/com/google/crypto/tink/CryptoFormat.java Here's my reflection code that fails:
    Copy code
    val field = CryptoFormat::class.java.getDeclaredField("NON_RAW_PREFIX_SIZE")
    
         field.isAccessible = true
         
         val modifers = field.javaClass.getDeclaredField("modifiers")
         modifers.isAccessible = true
         modifers.setInt(field, field.modifiers and java.lang.reflect.Modifier.FINAL.inv())
         
         field.setInt(null, 2000)
    
         val newValue = CryptoFormat.NON_RAW_PREFIX_SIZE
         println("NON_RAW_PREFIX_SIZE is now: $newValue")
    Error:
    java.lang.NoSuchFieldException: modifiers
    e
    k
    • 3
    • 7
  • e

    Emil Kantis

    03/15/2024, 9:19 AM
    Is there any way to get the name of a parameter as
    String
    ? e.g.
    Copy code
    fun add(a: Int, b: Int) {
      println("${a::name} is $a") // a is 5
    }
    s
    a
    • 3
    • 3
  • j

    Johannes Wirde

    05/15/2024, 9:43 AM
    Hello, everyone! 👋 How do I declare a interface using Kotlin reflections? KClass is missing "isInterface" and
    KClassifier.createType
    throws on me because the internal descriptor is null/faulty (found at
    core/reflection.jvm/src/kotlin/reflect/full/KClassifiers.kt:48
    , I'm using 2.0.0-RC1), I'm guesstimating it's because I have no constructors set, but this shouldn't be needed for an interface, right?
  • v

    v79

    05/23/2024, 8:52 PM
    Given a class definition
    class Request<I>(val body: I)
    can I get the
    KType
    of
    I
    when the
    Request
    is constructed? Nothing is reified and I definitely cannot call
    typeOf<I>
    .
    a
    • 2
    • 2
  • b

    Blake Anderson

    08/07/2024, 5:26 AM
    If I have a function with overloading, how can I get a
    KFunction
    reference to one of the overloads? I found I can use
    val ref: (String) -> Unit
    , for instance, as a way to disambiguate but the resulting type is not
    KFunction
    . It seems like I can cast this without everything crashing, but it's messy to use and not sure how stable that is.
    s
    e
    • 3
    • 5
  • c

    Cies

    08/21/2024, 7:21 PM
    Howdy all. I have a question. I have MVC controller classes and action methods (ehh functions) on those classes. The framework is in Java, but all our code is Kotlin. We looooooove KFunction and KClass as that allowed us to move away from string references to methods and classes as prescribed by the Java framework, giving us really cool type safety and refactorability. Anyway, the authorization is implemented with annotations on the controller classes and their methods. For example
    @RequiresAnyUserPermissionOf(...)
    that takes one or more permission enum instances. We check on each incoming request that that user user is allowed to the action by using reflection to get the annotation of the method and the class and all superclasses (up to some point). I consider caching all this by making some maps like
    Map<KFunction<Result>, List<Permission>>
    and
    Map<KClass<Controller>, List<Permission>>
    so it is all cached and we do not have to (recursively) reflect all over the place to now what permissions are on a certain controller class or controller action method. I have no clue what a KClass or KFunction actually is! Would this be a good idea? Or should I make these maps based on string representations (and the convert the KFunction or KClass to a string when doing a lookup)? Or doing a bunch of these reflections class to find the annotations soooooo fast that I should not bother at all... Just curious what you have to say on this, and as to how a KFunction or KClass actually is represented in memory.
    • 1
    • 1
  • m

    Moe

    09/13/2024, 5:54 PM
    Hello everyone I'm having trouble figuring out an unresolved reference I'm fairly certain i've used those imports before
    Copy code
    import kotlin.reflect.full.findAnnotation
     import kotlin.reflect.full.primaryConstructor
    but now all I'm getting is Unresolved reference: full although
    Copy code
    import kotlin.reflect.KClass
    seems to work perfectly fine.
    not sure what im missing to be honest, but any assistance would be highly appreciated This is happening in my JVM module, and it works fine in my androidMain. I have the dependency set to both. P.S Koltin 2.0.20 Reflect 2.0.20
    e
    • 2
    • 2
  • c

    Cies

    09/27/2024, 11:55 AM
    Just wanna spread some love: KFunction alone is enough of a reason to ditch Java and go all in on Kotlin. We've removed all the pesky string representations of methods from our codebase! from
    "some.package.ControllerName.actionMethod"
    we now use
    ControllerName::actionMethod
    : type safe, refactor friendly, less prone to bugs, and just plain stupid that this is still (2024!) not possible in Java. Thanks to whomever got this right in Kotlin, I enjoy my working life on the JVM a lot better since. 💚💛❤️
    k
    d
    u
    • 4
    • 24
  • n

    Nathan Castlehow

    11/04/2024, 1:37 AM
    Hi, I was wondering if any one has had an issue where when getting the value of a value class using get on the Kproperty, get returns not null even if the property is actually null. It correctly returns null when directly grabbing the property
    OuterClass::valueClass
    but not when using the KProperty returned form
    OuterClass::class.declaredMemberProperties
    Minimum repro in thread🧵
    u
    • 2
    • 2
  • g

    groostav

    11/05/2024, 6:04 AM
    oook
    Copy code
    val x = fun(arg: String) { println(arg) }
    
    val functionRef: KFunction<*> = x::invoke //valid, i can create a reflective handle to invoke.
    
    x::class.members // 6 entries, 2 each of equals, hashcode, tostring. invoke is missing
    is this expected behaviour?
    e
    • 2
    • 5
  • g

    groostav

    11/05/2024, 6:06 AM
    I just put in a bunch of work to convert some code to kotlin from java, and it looks like ill have to convert it back unless i can figure out how to get
    ::invoke
    off a
    KClass
    instance
    c
    k
    • 3
    • 5
  • j

    Jason

    11/08/2024, 8:16 PM
    Does the Kotlin reflection API's work in KMP? I see some support but not a whole lot. I really need to get functions from a given instance who have a particular annotation.
    🚫 1
  • a

    Andrey V

    11/17/2024, 12:35 AM
    I'm observing unexpected behavior with
    KClass<*>.declaredMemberProperties
    . In the following code example:
    Copy code
    data class A<T001>(
        val a001:Int?=null,
        val a002:Double?=null,
        val a003:Int?=null,
        val a004:Double?=null,
        val a005:Int?=null,
        var a007:Double?=null,
        val a008:Int?=null,
    ) {
        var a006: T001? = null
        val a009 = ""
        fun <T002> x() {}
    }
    A::class.declaredMemberProperties
    provides a list of properties in the order
    listOf(::a001, ::a002, ::a003, ::a004, ::a005, ::a006, ::a007, ::a008, ::a009)
    , whereas at the java level, via
    A::class.java.declaredMethods.filter { it.name.startsWith("get") }
    , we get the expected order of properties declared in the primary constructor then properties declared in the body. Why does that happen?
    v
    e
    • 3
    • 6
  • a

    Andrey V

    11/17/2024, 12:39 AM
    I get that declaredMembers (and its subsets) is a List as an implementation detail, but is there a way to use kotlin's reflection to get the declared members in source order, more specifically in that primary constructor declared parameters come first in the list before the rest? (well, without querying the compiler-generated copy method to get the names of the parameters to use as a filter)
    d
    e
    • 3
    • 3
  • g

    Gergely Kőrössy

    11/23/2024, 4:24 AM
    I have a metadata / reflect question. How can I get the
    KClass
    or
    Class
    from a
    KmType
    ? For example, I have a
    KmType
    with the classifier being
    KmClassifier.Class
    which gives the name
    kotlin/collections/List
    . I have tried
    Class.forName(...)
    with it by replacing the
    /
    with
    .
    , but it doesn't work because the JVM type is actually
    java.util.List
    , so it throws a
    ClassNotFoundException
    for
    kotlin.collections.List
    . This is also true for things like
    kotlin/Float
    . Anyone knows a solution for this problem?
  • m

    marcinmoskala

    12/13/2024, 12:51 PM
    Is there a way to check in Kotlin Multiplatform is KType is a subtype of a different KType? I need something that will tell that
    typeOf<List<Dog>>
    is a subtype of
    typeOf<Iterable<Animal>>
  • e

    Eric

    12/18/2024, 2:40 PM
    I'd like to enforce that JPA entities w/ child collections of type
    MutableSet
    have
    orphanRemoval = true
    on the
    @OneToMany
    annotation, but I can't figure out a good way to detect that using reflection. This works, but I don't like using
    toString
    since that might change. Is there another way that I'm missing that I could use to find all properties that are not an immutable Set?
    Copy code
    @Test
        fun test() {
            val valid = LotEntity::class.declaredMemberProperties
                .asSequence()
                .filter { it.returnType.isSubtypeOf(Collection::class.starProjectedType) }
                .filterNot { it.returnType.toString().startsWith("kotlin.collections.Set") }
                .mapNotNull { it.javaField?.getAnnotation(OneToMany::class.java) }
                .all { oneToMany -> oneToMany.orphanRemoval }
            println(valid)
        }
  • j

    Josh Feinberg

    01/10/2025, 3:03 AM
    i have an interface whose function has a default value but when i try to call its implementation via reflection i cannot call it as it says the parameter is missing
    e
    • 2
    • 12
  • a

    Andrey V

    01/13/2025, 9:00 AM
    I'm getting a strange issue with
    callBy
    In which cases, for
    @Serializable data class C
    and applicable primary constructor params
    ...
    , can the following expression
    Copy code
    ((::C).call(...)::copy).callBy(emptyMap())
    fail with
    Copy code
    KotlinReflectionInternalError(
        "Inconsistent number of parameters in the descriptor and Java reflection object: $arity != $expectedArgsSize\n" +
                "Calling: $descriptor\n" +
                "Parameter types: ${this.parameterTypes})\n" +
                "Default: $isDefault
    with
    expectedArgsSize
    being the number of primary constructor declared properties + 1 and arity being the number of primary constructor declared properties + 2? It seems the -1 is due to the reflection logic determining that it's a bound reference to a static method, which seems nonsensical Reducing the case to ~100 lines made the issue vanish so I'm looking for things to pay attention to for debugging
    • 1
    • 1
  • d

    DamianReeves

    02/06/2025, 12:10 AM
    Is it possible to create a KClass from within Java?
    e
    • 2
    • 5
  • r

    rad

    03/03/2025, 6:37 PM
    https://pastes.dev/xrBzbrlsTG I'm having this weird exception when getting the return type of a
    KProperty<*>
    in a delegate like such:
    Copy code
    operator fun <T : GameDataEntry> getValue(
            thisRef: Any?,
            property: KProperty<*>
        ): T {
            @Suppress("UNCHECKED_CAST")
            return requireNotNull(getData(property.returnType.classifier as KClass<T>))
        }
    Using Kotlin 2.1.10, is this a bug or am I just doing something wrong? The exception happens even when just attempting to get the
    returnType
    c
    • 2
    • 4