1

我需要BuilderKotlinPoet. 为此,我需要让方法返回Builder类型。我通过以下方式进行操作:

    private fun generateInitUserBehaviorClass() = TypeSpec.classBuilder("Init")
    .addType(generateInitBuilderClass())
    .build()

private fun generateInitBuilderClass() = TypeSpec.classBuilder("Builder")
    .addProperty(generateInitBuilderEndpointProperty())
    .addFunction(generateInitBuilderEndpointSetter())
    .build()

private fun generateInitBuilderEndpointProperty() = PropertySpec.builder(
    "endpoint",
    Class.forName("android.net.Uri").asTypeName().copy(nullable = true),
    KModifier.PRIVATE
).mutable(true)
    .initializer("null")
    .build()

private fun generateInitBuilderEndpointSetter() = FunSpec.builder("setEndpoint")
    .addParameter("endpoint", Class.forName("android.net.Uri"))
    .returns(Class.forName("com.idfinance.userbehavior.utils.Init.Builder"))
    .build()

但是当我构建模块时,我发现了Class.forName("com.idfinance.userbehavior.utils.Init.Builder")找不到 class的错误Builder。该包是正确的,据我所知,问题是我在尚未生成类时尝试将其用作返回类型。但是我该如何解决这个问题呢?

4

1 回答 1

1

您可以ClassName使用其构造函数实例化 a ,它不必是已声明的类:

private fun generateInitBuilderEndpointSetter() = FunSpec.builder("setEndpoint")
    .addParameter("endpoint", ClassName("android.net", "Uri"))
    .returns(ClassName("com.idfinance.userbehavior.utils", "Init", "Builder"))
    .build()
于 2021-07-28T14:13:58.717 回答