Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 737
tango24 Avatar asked Mar 09 '23 14:03

tango24


1 Answers

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`
like image 88
holi-java Avatar answered Mar 15 '23 18:03

holi-java