Kapt: Attach generated Kotlin sources in 'compilation' mode (KT-32535)
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
package test
|
||||
|
||||
import apt.Anno
|
||||
import generated.Test as TestGenerated
|
||||
|
||||
@Anno
|
||||
class Test {
|
||||
@field:Anno
|
||||
val property: String = ""
|
||||
|
||||
@Anno
|
||||
fun function() {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
fun main() {
|
||||
println("Generated class: " + TestGenerated::class.java.name)
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
apt.SampleApt
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package apt
|
||||
|
||||
import java.io.File
|
||||
import javax.annotation.processing.*
|
||||
import javax.lang.model.SourceVersion
|
||||
import javax.lang.model.element.TypeElement
|
||||
import javax.tools.Diagnostic.Kind.*
|
||||
|
||||
annotation class Anno
|
||||
|
||||
class SampleApt : AbstractProcessor() {
|
||||
private companion object {
|
||||
const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated"
|
||||
}
|
||||
|
||||
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
|
||||
val kaptKotlinGeneratedDir = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME] ?: run {
|
||||
processingEnv.messager.printMessage(ERROR, "Can't find the target directory for generated Kotlin files.")
|
||||
return false
|
||||
}
|
||||
|
||||
val baseDir = File(kaptKotlinGeneratedDir, "generated")
|
||||
baseDir.mkdirs()
|
||||
|
||||
for (element in roundEnv.getElementsAnnotatedWith(Anno::class.java)) {
|
||||
val generatedSimpleName = element.simpleName.toString().capitalize()
|
||||
val file = File(baseDir, "$generatedSimpleName.kt")
|
||||
file.writeText("package generated\nclass $generatedSimpleName")
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
override fun getSupportedOptions() = emptySet<String>()
|
||||
override fun getSupportedSourceVersion() = SourceVersion.RELEASE_8
|
||||
override fun getSupportedAnnotationTypes() = setOf("apt.Anno")
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# mkdir
|
||||
output/ap
|
||||
output/stubs
|
||||
output/classes
|
||||
output/sources
|
||||
output/kotlin-sources
|
||||
|
||||
# kotlinc
|
||||
-cp %KOTLIN_STDLIB%
|
||||
-d output/ap
|
||||
ap/Processor.kt
|
||||
|
||||
# copy
|
||||
ap/META-INF/services/javax.annotation.processing.Processor
|
||||
output/ap/META-INF/services/javax.annotation.processing.Processor
|
||||
|
||||
# kapt
|
||||
-Kapt-stubs=output/stubs
|
||||
-Kapt-classes=output/classes
|
||||
-Kapt-sources=output/sources
|
||||
-Kapt-classpath=output/ap
|
||||
-Kapt-option:kapt.kotlin.generated=output/kotlin-sources
|
||||
-d output/classes
|
||||
-cp output/ap:%KOTLIN_STDLIB%
|
||||
Test.kt
|
||||
|
||||
# java
|
||||
-cp output/classes:output/ap:%KOTLIN_STDLIB%
|
||||
test.TestKt
|
||||
|
||||
# after
|
||||
Generated class: generated.Test
|
||||
Reference in New Issue
Block a user