@@ -14,6 +14,7 @@ import org.gradle.api.Project
1414import org.gradle.api.Task
1515import org.gradle.api.UnknownTaskException
1616import org.gradle.api.artifacts.Configuration
17+ import org.gradle.api.logging.Logger
1718import org.gradle.api.provider.Provider
1819import org.gradle.api.tasks.TaskContainer
1920import 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+
538563internal fun KotlinCompilation <* >.kaptConfigName (): String {
539564 return addPrefixToSourceSetName(" kapt" , sourceSetName())
540565}
0 commit comments