gpt4 book ai didi

Kotlin 反射包并获取所有类

转载 作者:行者123 更新时间:2023-12-05 06:21:15 24 4
gpt4 key购买 nike

如何反射(reflect)一个包并将所有类列为 KClass<*>?

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

最佳答案

这是我的解决方案。

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

关于Kotlin 反射包并获取所有类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59936471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com