Skip to content

Commit

Permalink
Properly handle sealed classes with Kotlin 1.7 and JDK 17
Browse files Browse the repository at this point in the history
  • Loading branch information
stuebingerb committed Sep 6, 2022
1 parent 80c7ea3 commit 5f70333
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
Expand Up @@ -25,9 +25,10 @@ class ObjenesisInstantiator(
@Suppress("UNCHECKED_CAST")
return Any() as T
} else if (cls.isSealedSafe()) {
cls.getPermittedSubclassesSafe().firstNotNullOfOrNull { subCls ->
@Suppress("UNCHECKED_CAST")
return cls.getPermittedSubclassesSafe().firstNotNullOfOrNull { subCls ->
runCatching { instance(subCls) }.getOrNull()
} ?: error("could not find subclass for sealed class $cls")
} as T ?: error("could not find subclass for sealed class $cls")
} else if (!Modifier.isFinal(cls.modifiers)) {
try {
val instance = instantiateViaProxy(cls)
Expand Down Expand Up @@ -55,7 +56,7 @@ class ObjenesisInstantiator(
javaClass.methods.firstOrNull { it.name == "isSealed" }?.invoke(this) == true

/**
* `Class<?>[] Class.getPermittedSubclasses` is only available with JDK 17+. Used via reflection
* `Class<?>[] Class.getPermittedSubclasses()` is only available with JDK 17+. Used via reflection
* to support builds with previous Java versions as well. This should be refactored to use the
* actual method once the minimum Java version is 17.
*/
Expand Down
Expand Up @@ -105,6 +105,12 @@ internal class ProxyMaker(
} else if (interfaces.isEmpty() && !Modifier.isAbstract(clazz.modifiers) && inliner != null) {
log.trace("Taking instance of $clazz itself because it is not abstract and no additional interfaces specified.")
clazz
} else if (clazz.kotlin.isSealed) {
log.trace("Taking instance of subclass because it is sealed.")
clazz.kotlin.sealedSubclasses.firstNotNullOfOrNull {
@Suppress("UNCHECKED_CAST")
subclass(it.java, interfaces) as Class<T>
} ?: error("Unable to create proxy for sealed class $clazz")
} else {
log.trace(
"Building subclass proxy for $clazz with " +
Expand Down

0 comments on commit 5f70333

Please sign in to comment.