Home > Software engineering >  Get child from field via reflection
Get child from field via reflection

Time:04-08

So i have a class like this

class Fragment{
   private val binding: MyFragmentBinding
}

MyFragmentBinding has a private field "webView", which I want to access.

First step:

val firstField = fragment.javaClass.getDeclaredField("binding")

This works and I got a field with my binding class. But in this class I want to access the field with the name "webView". How can I do this?

CodePudding user response:

Get the referenced object, and then repeat the whole process for the field in that object.

val binding = fragment.javaClass.getDeclaredField("binding").get(fragment)
val webView = binding.javaClass.getDeclaredField("webView").get(binding)
  • Related