File tree Expand file tree Collapse file tree 1 file changed +12
-7
lines changed
src/main/kotlin/com/lambda/util/reflections Expand file tree Collapse file tree 1 file changed +12
-7
lines changed Original file line number Diff line number Diff line change @@ -25,24 +25,29 @@ import io.github.classgraph.Resource
2525import io.github.classgraph.ResourceList
2626import io.github.classgraph.ScanResult
2727import java.lang.reflect.Modifier
28- import kotlin.jvm.java
2928
3029val scanResult: ScanResult by lazy { ClassGraph ().enableAllInfo().scan() }
3130
31+ /* *
32+ * This function returns a instance of subtype [T].
33+ *
34+ * When [T] is an interface, the function with returns a list of classes that implements [T].
35+ * When [T] is an abstract class (open classes too), the function will return a list of classes extending [T].
36+ *
37+ * Only final classes with empty constructors will be created.
38+ */
3239inline fun <reified T : Any > getInstances (crossinline block : (ClassInfo ) -> Boolean = { true }): List <T > {
3340 if (scanResult.isClosed) return emptyList()
3441
3542 val clazz = T ::class .java
3643
3744 return when {
3845 clazz.isInterface -> scanResult.getClassesImplementing(clazz)
39- .filter { block(it) }
40-
41- clazz.isObject || Modifier .isAbstract(clazz.modifiers) -> scanResult.getSubclasses(clazz)
42- .filter { block(it) }
46+ Modifier .isAbstract(clazz.modifiers) -> scanResult.getSubclasses(clazz)
4347
44- else -> throw IllegalAccessException (" class ${clazz.name} is neither an interface or open class" )
45- }.mapNotNull { createInstance<T >(Class .forName(it.name)) }
48+ else -> throw IllegalStateException (" class ${clazz.name} is neither an interface or open class" )
49+ }.filter { block(it) }
50+ .mapNotNull { createInstance<T >(Class .forName(it.name)) }
4651}
4752
4853inline fun getResources (pattern : String , crossinline block : (Resource ) -> Boolean ): ResourceList =
You can’t perform that action at this time.
0 commit comments