dimanche 6 septembre 2020

Kotlin Reflection Accessing Java Field Accessors (Getter and Setter)

I have the following java class

_17_A.java

package _z_additional;

public class _17_A {
    private int x = 0;

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }
}

I am trying to obtain instances of the accessors of the java fields inside the class _17_A using the following Kotlin code (and Kotlin reflection)

_17_ObtainingJavaAccessors_Test.kt

package _z_additional

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import java.lang.reflect.Method
import kotlin.reflect.KClass
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.javaGetter
import kotlin.reflect.jvm.javaMethod

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
object _17_ObtainingJavaAccessors_Test {

    @Test
    fun demonstrate() {
        val cls: KClass<*> = _17_A::class
        cls.declaredMemberProperties.forEach {
            val getter1: Method? = it.javaGetter
            val getter2: Method? = it.getter.javaMethod
            println("getter1 = ${getter1}")
            println("getter2 = ${getter2}")
        }
    }

}

Output

getter1 = null
getter2 = null

The problem is that i am getting nulls





Aucun commentaire:

Enregistrer un commentaire