user2545386
user2545386

Reputation: 457

Can I use kotlin.reflect to get a value of a field

class A{
     private var p:MyObj? = null
}

It seems that I can't get p by A::p, Or I can only get it by java?

My kotlin version is

ext.kotlin_version = '1.1.4-2'

Upvotes: 2

Views: 1802

Answers (1)

Mibac
Mibac

Reputation: 9448

You can't get it because you do it outside of that class when the property is private. You have a few options here:

  1. create a function returning this::p (fun func(): KProperty0<MyObj?> = this::p)
  2. make that property public
  3. use reflection. This is probably the slowest, least performant and very tightly coupled option. Use it only if you can't use the others. You can use Kotlin's reflection like so: A::class.memberProperties.find { it.name == "p" } as KProperty1<A, MyObj?>

Upvotes: 2

Related Questions