dimanche 20 février 2022

Using Kotlin reflection how to determine which constructor parameters were given as `val`?

Simple case A (no problem here)

class A(val title: String)

For instance a, we will get the parameters list from a.javaClass.kotlin.primaryConstructor!!.valueParameters.

Simple case B (no problem here)

class B(titleRaw: String) {             // no val
  val titleFinal = titleRaw.uppercase() // the property has different name
}

We can determine that the titleRaw parameter does not create a property because there is no titleRaw property on the object. We will use valueParameters and memberProperties to detect that.

Difficult case:

class C(title: String) {        // no val
  val title = title.uppercase() // property with the same name
}

How to detect that the title property does not return the value of the title parameter?

A little background

Having an instance of a class, I want to know what constructor argument values it was instantiated with. If that's not possible (the primary constructor takes arguments that aren't properties), I'd like to throw an exception.





Aucun commentaire:

Enregistrer un commentaire