Bradley Campbell
Bradley Campbell

Reputation: 9808

How to generate a kotlin file from an annotation processor?

I have a java annotation processor which generates a bunch of java files during compilation. I'd like to make the generated classes nicer to use in kotlin by adding extension methods. I've been told on the kotlin forums that something I could try would be to write a kotlin file that contains my extension functions. I've tried this, I used the Filer object to create this file outputting it to the StandardLocations.SOURCE_OUTPUT directory. Intellij can see my generated class, and I can use the extension functions as intended, but the app won't compile because the compiler can't find the new kotlin file. Is there any way I can write a new kotlin file that'll get picked up by the kotlin compiler?

Upvotes: 20

Views: 2302

Answers (2)

Fabian Zeindl
Fabian Zeindl

Reputation: 5988

Output your files (with proper package names) into a directory like src/build/generated-src/kotlin/your/package/File.kt

and add this to your build.gradle:

sourceSets {
    main.java.srcDirs += 'build/generated-src/kotlin'
}

Upvotes: 0

Alexander Blinov
Alexander Blinov

Reputation: 393

For kapt you can get source folder via.

Map<String, String> options = processingEnv.getOptions();
                String generatedPath = options.get("kapt.kotlin.generated");

String path = generatedPath
                    .replaceAll("(.*)tmp(/kapt/debug/)kotlinGenerated",
                            "$1generated/source$2");

Unfortunately it doesn't work for kapt2 (see issue KT-14070)

You also can create .kt files via resource writer

Writer w = processingEnv.getFiler().createResource(SOURCE_OUTPUT, "package_name", "Sample.kt")

But for now you need to invoke compiler twice cause compileDebugKotlin task runs before invoking javax annotation processor by compileDebugJavaWithJavac task)

Upvotes: 2

Related Questions