Skip to content

Commit 72f48cf

Browse files
authored
Add reflective fallback for useK2 to support Kotlin 2.3.0+ (#95)
1 parent 44c7a3f commit 72f48cf

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

gradle-plugin/src/main/java/com/squareup/anvil/plugin/AnvilPlugin.kt

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import org.gradle.api.Project
1414
import org.gradle.api.Task
1515
import org.gradle.api.UnknownTaskException
1616
import org.gradle.api.artifacts.Configuration
17+
import org.gradle.api.logging.Logger
1718
import org.gradle.api.provider.Provider
1819
import org.gradle.api.tasks.TaskContainer
1920
import org.gradle.api.tasks.TaskProvider
@@ -111,8 +112,7 @@ internal open class AnvilPlugin : KotlinCompilerPluginSupportPlugin {
111112
kotlinCompilation: KotlinCompilation<*>,
112113
): Provider<List<SubpluginOption>> {
113114
kotlinCompilation.compilerOptions.options.let {
114-
@Suppress("DEPRECATION")
115-
val useK2 = it.useK2.get()
115+
val useK2 = getUseK2Value(it, kotlinCompilation.project.logger)
116116
if (useK2 || it.languageVersion.getOrElse(KOTLIN_1_9) >= KOTLIN_2_0) {
117117
kotlinCompilation.project.logger
118118
.error(
@@ -535,6 +535,31 @@ private fun addPrefixToSourceSetName(
535535
else -> "${prefix}${sourceSetName.capitalize()}"
536536
}
537537

538+
/**
539+
* Determines whether the K2 compiler should be used by attempting to read the `useK2`
540+
* property via reflection. This allows compatibility with both Kotlin versions that
541+
* expose the property and versions that do not.
542+
*
543+
* If the property or its provider cannot be accessed, the method safely falls back to the
544+
* default behavior (true for Kotlin 2.3.0+).
545+
*
546+
* @param options The KotlinCompilerOptions instance to inspect.
547+
* @param logger The logger used for reporting reflection-related decisions.
548+
* @return true if K2 is enabled or defaults to enabled; false only if the property exists
549+
* and explicitly returns false.
550+
*/
551+
private fun getUseK2Value(options: Any, logger: Logger): Boolean =
552+
runCatching {
553+
val useK2Method = options.javaClass.getMethod("getUseK2")
554+
val useK2Provider = useK2Method.invoke(options) as? Provider<*>
555+
?: return false
556+
557+
useK2Provider.get() as Boolean
558+
}.getOrElse { e ->
559+
logger.info("useK2 reflection check failed, defaulting to true (useK2 = true): ${e.message}")
560+
true
561+
}
562+
538563
internal fun KotlinCompilation<*>.kaptConfigName(): String {
539564
return addPrefixToSourceSetName("kapt", sourceSetName())
540565
}

0 commit comments

Comments
 (0)