我想生成这样的代码:
class B private constructor() : A {
companion object {
val instance: B by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
B()
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用 KotlinPoet:
private fun genCompanionObject() = TypeSpec.companionObjectBuilder()
.addProperty(PropertySpec.builder("instance", A::class.java).build()).build()
Run Code Online (Sandbox Code Playgroud)
如何生成by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED)?我在文档中找不到一些有用的API 。
你正在寻找PropertySpec.Builder.delegate方法。您提供CodeBlock代表代表委托的初始值设定项。
特别针对您想要的代码:
.delegate(CodeBlock.builder()
.beginControlFlow("lazy(mode = %T.SYNCHRONIZED)", LazyThreadSafetyMode::class.asTypeName())
.add("B()") // Or however you want to implement this
.endControlFlow()
.build())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
811 次 |
| 最近记录: |