Home > OS >  Simple reflection in Kotlin doesn't work in existing Java project
Simple reflection in Kotlin doesn't work in existing Java project

Time:10-27

I have simple Kotlin code in an existing Java project

class A(val p: Int)

fun main() {
    println("Hello World")
    println(A::javaClass)
    println(A::p)
}

However, this throws an exception

Exception in thread "main" java.lang.NoSuchMethodError: 'void kotlin.jvm.internal.PropertyReference1Impl.(java.lang.Class, java.lang.String, java.lang.String, int)'

build.gradle.kts is also simple

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.7.20"
}

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-reflect:1.7.20")
}

tasks.test {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = "17"
}

Verified that kotlin-reflect is also listed in runtimeClassPath. However, the same code works in a Kotlin-only project.

CodePudding user response:

This sounds more like a mismatch in the kotlin stdlib during runtime and a compiled class, not something related to reflection (but I'm not very familiar with reflection so I could be wrong).

It seems like the method with signature

PropertyReference1Impl(java.lang.Class, java.lang.String, java.lang.String, int)

Was added in kotlin 1.4, also see this for another example of the same error.

Not really sure where you kotlin < 1.4 stuff is coming from though, are you perhaps using an old gradle version (although I'm not even sure if that would matter)?

Please also add the full stacktrace to the question, instead of just 1 line, that should show what exactly is attempting to call the missing method.

CodePudding user response:

Use ::class.java instead of ::javaClass.

The documentation isn't clear about this, but you don't need the kotlin-reflect library for basic property, function, and class references. You only need it for the deeper features like getting the class/property/function members or descriptors. Passing around KClasses, KProperties, and KFunction instances or invoking them doesn't require the library.

  • Related