0

If I have a Kotlin class like the following:

data class Foo(
    val count: AtomicInteger
) {
    init {
        count.incrementAndGet()
    }
}

How do I determine that this class has an init block using reflection?

The init block does not appear in Foo::class.members and I can't see a way of determining it from Foo::class.constructors.

Is there any way to find out information about the init block using kotlin.reflect?

David Rawson
  • 20,912
  • 7
  • 88
  • 124
  • 1
    I highly doubt this information is available after compilation. Init blocks and property initializers on JVM are compiled into some mixture of constructors and/or field initializers. It’s up to the compiler how it wants to do this in an optimal way. – Tenfour04 Sep 28 '21 at 21:24
  • @Tenfour04 thanks, I was hoping it would be somehow available in the Kotlin metadata and accessible using reflection but no luck so far – David Rawson Sep 28 '21 at 21:28
  • why do you need it? – IR42 Sep 28 '21 at 21:32
  • @IR42 dealing with a legacy system that still uses Gson and can't be migrated any time soon :/ When Gson constructs an instance it doesn't run the init block, so I wanted to catch this somehow. – David Rawson Sep 28 '21 at 21:46
  • Does Gson call a constructor? If so, then that will include anything needed in `init` blocks too. (Or if not, then that's probably the larger problem.) – gidds Sep 28 '21 at 22:09
  • @gidds unfortunately Gson uses unsafe calls to construct the instance, so it is indeed a larger problem. – David Rawson Sep 28 '21 at 22:13
  • @Tenfour04 I believe your comment is correct, if you change it into an answer I will accept it – David Rawson Sep 29 '21 at 07:26

1 Answers1

0

This information is not available after compilation.

Init blocks and property initializers on JVM are compiled into some mixture of constructors and/or field initializers. It’s up to the compiler how it wants to do this in an optimal way.

Answer courtesy of Tenfour04

David Rawson
  • 20,912
  • 7
  • 88
  • 124