首页 > 解决方案 > Kotlin 多平台注释处理

问题描述

Kotlin Multiplatform 中的注释处理可以在kapt有 jvm 目标时完成。

但是如果没有 jvm 目标,如何处理注释呢?

具体来说,我想在处理来自commonMain. 但我不知道如何处理这些。

我的注释处理器现在只记录:

@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes("ch.hippmann.annotation.Register")
@SupportedOptions(RegisterAnnotationProcessor.KAPT_KOTLIN_GENERATED_OPTION_NAME)
class RegisterAnnotationProcessor : AbstractProcessor(){

    companion object {
        const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated"
    }

    override fun process(annotations: MutableSet<out TypeElement>?, roundEnv: RoundEnvironment?): Boolean {
        processingEnv.messager.printMessage(Diagnostic.Kind.WARNING, "Processing")
        return true
    }


}

注释位于单独的多平台模块中,位于commonMain

@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class Register

并在项目中使用commonMain
部分build.gradle

kotlin {
    jvm()
    // For ARM, should be changed to iosArm32 or iosArm64
    // For Linux, should be changed to e.g. linuxX64
    // For MacOS, should be changed to e.g. macosX64
    // For Windows, should be changed to e.g. mingwX64
    linuxX64("linux")
    sourceSets {
        commonMain {
            dependencies {
                implementation kotlin('stdlib-common')
                implementation project(":annotations")
            }
        }
        commonTest {
            dependencies {
                implementation kotlin('test-common')
                implementation kotlin('test-annotations-common')
            }
        }
        jvmMain {
            dependencies {
                implementation kotlin('stdlib-jdk8')
            }
        }
        jvmTest {
            dependencies {
                implementation kotlin('test')
                implementation kotlin('test-junit')
            }
        }
        linuxMain {
        }
        linuxTest {
        }
    }
}

dependencies {
    kapt project(":annotationProcessor")
}

jvm()当存在目标时,这就像日志一样工作。但是如果我删除它,我不能使用kapt.

那么在没有 jvm目标的情况下如何处理注解呢?

标签: kotlinannotationsannotation-processingkotlin-multiplatformkapt

解决方案


你似乎已经解决了你的问题,但如果有人最终来到这里......

我可以在没有任何问题的情况下在通用代码上使用 kapt,如下所示:

val commonMain by getting {
    dependencies {
        ...
         configurations.get("kapt").dependencies.add(project(": annotationProcessor"))
    }
}

commonMain它可以毫无问题地处理代码上的注释。不过,我确实有一个 android 目标,所以如果问题仅在根本没有 jvm 目标时出现,那么 ymmv。还有一些注释处理器适用于 Kotlin Native,例如https://github.com/Foso/MpApt


推荐阅读