0

我尝试使用注释处理器和 Kotlin Poet 创建一个类。这是我的代码:

@AutoService(Processor::class)
class TailProcessor : AbstractProcessor() {

    override fun process(elementTypeSet: MutableSet<out TypeElement>?, roundEnvironment: RoundEnvironment?): Boolean {
        roundEnvironment?.getElementsAnnotatedWith(Tail::class.java)?.forEach {
            if (it.javaClass.kotlin.isData) {
                print("You are doing it right")
                val className = it.simpleName.toString()
                val pack = processingEnv.elementUtils.getPackageOf(it).toString()
                val variables = ElementFilter.fieldsIn(elementTypeSet)
                startClassGeneration(className, pack, variables)
            } else {
                return false
            }
        }
        return false
    }

    override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latest()

    override fun getSupportedAnnotationTypes(): MutableSet<String> = mutableSetOf(Tail::class.java.name)

    private fun startClassGeneration(
        className: String,
        pack: String,
        variables: MutableSet<VariableElement>
    ) {
        val fileName = "Tail$className"
        val stringToBePrinted = generateStringFromIncommingValues(variables)
        val printFunction = FunSpec.builder("print").addCode("print($stringToBePrinted)").build()
        val generatedClass = TypeSpec.objectBuilder(fileName).addFunction(printFunction).build()
        val file = FileSpec.builder(pack, fileName).addType(generatedClass).build()
        val kaptKotlinGeneratedDir = processingEnv.options[KOTLIN_DIRECTORY_NAME]
        file.writeTo(File(kaptKotlinGeneratedDir, "$fileName.kt"))
    }

    private fun generateStringFromIncommingValues(variables: MutableSet<VariableElement>): Any {
        val stringBuilder = StringBuilder()
        variables.forEach {
            if (it.constantValue == null) {
                stringBuilder.append("null\n ")
            } else {
                stringBuilder.append("${it.constantValue}\n")
            }
        }
        return stringBuilder.toString()
    }

    companion object {
        const val KOTLIN_DIRECTORY_NAME = "sxhardha.tail"
    }
}

问题,目录和文件未生成。我试图重建,使缓存无效+重新启动,清理但它们都不起作用。构建成功,没有任何错误,但我没有看到任何变化。你能检查出什么问题吗?

4

1 回答 1

0

我确实发现了这个问题。我没有检查该班级是否是data班级并且从未满足条件。

代替:

it.javaClass.kotlin.isData

本来应该:

it.kotlinMetadata as KotlinClassMetadata).data.classProto.isDataClass

但它只能通过在这里使用这个库来实现

于 2019-05-29T14:37:38.323 回答