@@ -19,25 +19,11 @@ package com.lambda.util.reflections
1919
2020import com.lambda.util.extension.isObject
2121import com.lambda.util.extension.objectInstance
22- import org.reflections.Reflections
22+ import io.github.classgraph.ClassGraph
23+ import io.github.classgraph.ResourceList
2324import org.reflections.util.ConfigurationBuilder
2425import java.lang.reflect.Modifier
25- import java.util.*
26-
27- val cache = mutableMapOf<Int , Reflections >()
28-
29- /* *
30- * This function retrieves or create a reflection instance to avoid redundant
31- * reflection calls
32- *
33- * Every time you instantiate a [Reflections] class, it scans the entire classloader and caches its result in a store
34- */
35- inline fun reflectionCache (block : ConfigurationBuilder .() -> Unit ): Reflections {
36- val config = ConfigurationBuilder ().apply (block)
37- val cacheKey = Objects .hash(config.classLoaders, config.urls, config.scanners, config.inputsFilter)
38-
39- return cache.getOrPut(cacheKey) { Reflections (config) }
40- }
26+ import kotlin.jvm.java
4127
4228/* *
4329 * Retrieves all instances of the specified type `T`.
@@ -47,9 +33,21 @@ inline fun reflectionCache(block: ConfigurationBuilder.() -> Unit): Reflections
4733 *
4834 * @return A list of instances of type `T`
4935 */
50- inline fun <reified T : Any > getInstances (block : ConfigurationBuilder .() -> Unit = { forPackage("com.lambda") }) =
51- reflectionCache(block).getSubTypesOf(T ::class .java)
52- .mapNotNull { createInstance<T >(it) }
36+ inline fun <reified T : Any > getInstances (block : ClassGraph .() -> Unit = { enableClassInfo(); acceptPackages("com.lambda") }): List <T > =
37+ ClassGraph ().apply (block)
38+ .scan()
39+ .use { result ->
40+ val clazz = T ::class .java
41+
42+ return when {
43+ clazz.isInterface -> result.getClassesImplementing(T ::class .java)
44+
45+ clazz.isObject || Modifier .isAbstract(clazz.modifiers) ->
46+ result.getSubclasses(T ::class .java)
47+
48+ else -> throw IllegalAccessException (" class ${clazz.name} is neither an interface or abstract class" )
49+ }.mapNotNull { createInstance<T >(Class .forName(it.name)) }
50+ }
5351
5452/* *
5553 * Retrieves all resource paths that match the given pattern.
@@ -62,8 +60,10 @@ inline fun <reified T : Any> getInstances(block: ConfigurationBuilder.() -> Unit
6260 *
6361 * @return A set of resource paths that match the specified pattern.
6462 */
65- inline fun getResources (pattern : String , block : ConfigurationBuilder .() -> Unit = { forPackage("com.lambda") }) =
66- reflectionCache(block).getResources(pattern)
63+ inline fun getResources (pattern : String , block : ClassGraph .() -> Unit = { enableAllInfo(); acceptPackages("com.lambda") }): ResourceList =
64+ ClassGraph ().apply (block)
65+ .scan()
66+ .use { it.getResourcesMatchingWildcard(pattern) }
6767
6868inline fun <reified T : Any > createInstance (clazz : Class <* >): T ? {
6969 return when {
0 commit comments