Paul N
01/13/2023, 11:09 AMUnknown property 'someField' on class 'class rubbish.SomeKotlinClass'
Is there a way of making Kotlin POJO type classes 100% compatible with code like PropertyUtils that relies on Java reflection ?
// <https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils>
implementation("commons-beanutils:commons-beanutils:1.9.3")
package rubbish
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import org.apache.commons.beanutils.PropertyUtils
import org.junit.jupiter.api.Test
data class SomeKotlinClass(
@JvmField
var someField: String? = null,
)
class SetTest {
@Test
fun kotlinTestData() {
val x = SomeKotlinClass::class.java.getDeclaredConstructor().newInstance()
x.shouldNotBeNull()
val fields = SomeKotlinClass::class.java.declaredFields
fields.forEach {
println("Field is $it")
println("trying to get field")
SomeKotlinClass::class.java.getField(it.name)
println("got field")
}
PropertyUtils.setProperty(x,"someField","hello")
x.someField shouldBe "hello"
}
}
ephemient
01/13/2023, 11:14 AM@JvmField
properties should be compatible with Java Bean conventions. why did you need it?Paul N
01/13/2023, 11:26 AMephemient
01/13/2023, 11:35 AMdata class SomeKotlinClass(
var someField: String? = null,
)
fun main(vararg args: String) {
val x = SomeKotlinClass::class.java.getDeclaredConstructor().newInstance()
PropertyUtils.setProperty(x,"someField","hello")
println(x)
}
this works fine for me, prints SomeKotlinClass(someField=hello)
Paul N
01/13/2023, 11:39 AMSomeKotlinClass::class.java.getField("someField")
fails, but works if SomeKotlinClass is in Javaephemient
01/13/2023, 11:44 AMpublic
, which is a pretty terrible ideaephemient
01/13/2023, 12:05 PMclass SomeKotlinClass {
@JvmField
var someField: String? = null
fun getSomeField(): String? = someField
fun setSomeField(someField: String?) {
this.someField = someField
}
}
but Kotlin's not going to assist you with thatPaul N
01/13/2023, 1:35 PMPaul N
01/13/2023, 1:44 PM