Skip to content

Commit 861db72

Browse files
committed
Update Reflections.kt
1 parent 107d2ac commit 861db72

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

src/main/kotlin/com/lambda/util/reflections/Reflections.kt

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,24 +25,29 @@ import io.github.classgraph.Resource
2525
import io.github.classgraph.ResourceList
2626
import io.github.classgraph.ScanResult
2727
import java.lang.reflect.Modifier
28-
import kotlin.jvm.java
2928

3029
val 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+
*/
3239
inline 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

4853
inline fun getResources(pattern: String, crossinline block: (Resource) -> Boolean): ResourceList =

0 commit comments

Comments
 (0)