Kotlin 多平台注解处理

7

如果有JVM目标,可以使用kapt在Kotlin Multiplatform中进行注解处理。

但如果没有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目标的情况下如何处理注释呢?
1个回答

1

看起来您已经解决了问题,但如果有人最终来到这里...

我可以在通用代码中轻松使用kapt,就像这样:

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

它可以处理commonMain代码上的注释,没有任何问题。我确实有一个Android目标,所以如果问题只在完全没有jvm目标时出现,那么结果可能会有所不同。此外,对于Kotlin Native也有注释处理器可用,例如https://github.com/Foso/MpApt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接