4

Kotlin reflection library defines KDeclarationContainer, which Represents an entity which may contain declarations of any other entities, such as a class or a package.

this::class returns KClass, which extends KDeclarationContainer, but how do I get the parent KDeclarationContainer (a KPackage?)

tango24
  • 464
  • 2
  • 11

1 Answers1

8

There is no KPackage in kotlin now, but you can get a java Package instead, for example:

val pkg:Package = this::class.java.`package`

IF you really want to get a KPackageImpl instance, you can get it from kotlin.jvm.internal.Reflection, but it doesn't make sense, because Kotlin reflect is incomplete yet, for example:

val pkg = Reflection.getOrCreateKotlinPackage(this::class.java, "")
//  ^--- there is no methods to get package information like as java.lang.Package,
//       since it is a `KDeclarationContainer` rather than a `KPackage`
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • Thank you, but I was hoping for a kotlin equivalent. The check-in comment on https://github.com/JetBrains/kotlin/tree/master/core/builtins/src/kotlin/reflect actually mentions a `KPackage` – tango24 Jul 20 '17 at 09:39
  • Any progress on this in the last 5 years? I still don't see a `package` field on `KClass`. – Jorn Apr 16 '22 at 12:09