如何在KotlinPoet中为生成类实现Comparable<自身>?
如何用KotlinPoet让生成的类实现Comparable<自身>
嘿,我懂你现在的困惑啦——你已经拿到了要生成的类的ClassName,但不知道怎么用它来实现Comparable接口对吧?其实方法超直接,把你之前传的Any::class换成那个ClassName就行!
你之前的代码是这样的:
FileSpec.builder("com.fleshgrinder", "KotlinPoet").apply { val className = ClassName("com.fleshgrinder", "KotlinPoet") addType(TypeSpec.classBuilder(className).apply { addSuperinterface(ParameterizedTypeName.get(Comparable::class, Any::class)) }.build()) }.build().writeTo(System.out)
这段代码生成的是Comparable<Any>,但我们需要的是Comparable<KotlinPoet>。只需要把ParameterizedTypeName.get的第二个参数改成你定义好的className:
FileSpec.builder("com.fleshgrinder", "KotlinPoet").apply { val className = ClassName("com.fleshgrinder", "KotlinPoet") addType(TypeSpec.classBuilder(className).apply { // 把Any::class换成className addSuperinterface(ParameterizedTypeName.get(Comparable::class, className)) }.build()) }.build().writeTo(System.out)
这样生成的代码就完全符合你的期望了:
package com.fleshgrinder import kotlin.Comparable class KotlinPoet : Comparable<KotlinPoet>
为什么这样可行呢?因为ParameterizedTypeName.get的第二个参数接受的是TypeName类型,而ClassName是TypeName的子类,所以直接传入当前类的ClassName实例,就能正确生成Comparable<当前类>的接口声明啦。
内容的提问来源于stack exchange,提问作者Egor
相关产品推荐
相关产品推荐

