kapt: Support Kotlin code generation

This commit is contained in:
Yan Zhulanow
2015-07-14 16:35:10 +03:00
parent edb35ae6ce
commit 39d7e98775
6 changed files with 96 additions and 5 deletions
@@ -1,5 +1,6 @@
package example
import java.io.File
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
@@ -12,6 +13,8 @@ public class ExampleAnnotationProcessor : AbstractProcessor() {
private companion object {
val ANNOTATION_FQ_NAME = javaClass<ExampleAnnotation>().getCanonicalName()
val SUFFIX_OPTION = "suffix"
val GENERATE_KOTLIN_CODE_OPTION = "generate.kotlin.code"
val KAPT_KOTLIN_GENERATED_OPTION = "kapt.kotlin.generated"
}
override fun process(annotations: MutableSet<out TypeElement>?, roundEnv: RoundEnvironment): Boolean {
@@ -20,17 +23,27 @@ public class ExampleAnnotationProcessor : AbstractProcessor() {
val elementUtils = processingEnv.getElementUtils()
val filer = processingEnv.getFiler()
val generatedFileSuffix = processingEnv.getOptions().get(SUFFIX_OPTION) ?: "Generated"
val options = processingEnv.getOptions()
val generatedFileSuffix = options[SUFFIX_OPTION] ?: "Generated"
val generateKotlinCode = "true" == options[GENERATE_KOTLIN_CODE_OPTION]
val kotlinGenerated = options[KAPT_KOTLIN_GENERATED_OPTION]
for (element in elements) {
val packageName = elementUtils.getPackageOf(element).getQualifiedName().toString()
val className = element.getSimpleName().toString().capitalize() + generatedFileSuffix
val simpleName = element.getSimpleName()
val className = simpleName.toString().capitalize() + generatedFileSuffix
filer.createSourceFile(className).openWriter().use { with(it) {
appendln("package $packageName;")
appendln()
appendln("public final class $className {}")
}}
if (generateKotlinCode && kotlinGenerated != null && element.getKind() == ElementKind.CLASS) {
File(kotlinGenerated, "$simpleName.kt").writer().buffered().use {
it.appendln("package $packageName")
it.appendln("fun $simpleName.customToString() = \"$simpleName: \" + toString()")
}
}
}
return true;