Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a kotlin file from an annotation processor?

Tags:

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?

like image 220
Bradley Campbell Avatar asked Feb 02 '16 06:02

Bradley Campbell


Video Answer


1 Answers

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)

like image 57
Alexander Blinov Avatar answered Sep 18 '22 17:09

Alexander Blinov