4

How it is possible to reflect a package and list all classes as KClass<*>?

fun listAllClassesInPackage(pack: String): List<KClass<*>> = ...
fun main(args: Array<String>) {
    val classes: List<KClass<*>> = listAllClassesInPackage("com.example")
    classes.forEach { k ->
        println(k)
    }
}
Jayser
  • 371
  • 4
  • 15

2 Answers2

2

Here's my solution.

package com.example

import org.reflections.Reflections
import org.reflections.scanners.ResourcesScanner
import org.reflections.scanners.SubTypesScanner
import org.reflections.util.ClasspathHelper
import org.reflections.util.ConfigurationBuilder
import org.reflections.util.FilterBuilder

class Test1

fun op1() = ""

fun main(args: Array<String>) {
    val packagePath = "com.example"
    val reflections =
        Reflections(
            ConfigurationBuilder()
                .filterInputsBy(FilterBuilder().includePackage(packagePath))
                .setUrls(ClasspathHelper.forPackage(packagePath))
                .setScanners(SubTypesScanner(false))
        )
    val typeList = reflections.getSubTypesOf(Object::class.java)
    typeList.forEach { c ->
        println(c.kotlin)
    }
}
Jayser
  • 371
  • 4
  • 15
1

You should check out the kotlin reflekt plugin, though it isn't actively maintained anymore there is a working version for up to kotlin 1.7.0.

It allows you to simply call

Reflekt.classes().withSupertype<Any>().toSet().filter {
    it.kClass.java.package.name.startsWith("com.example")
}
uglibubla
  • 83
  • 11
  • [Link only answers](https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers/8259#8259) are considered very low quality and [can get deleted](https://stackoverflow.com/help/deleted-answers), please put the important parts from the linked resource into the answer body. – helvete May 11 '23 at 10:50