Search code examples
kotlinkotlin-reflect

How to get a kotlin package by reflection


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?)


Solution

  • 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`