com.squareup.inject.assisted.dagger2.processor.AssistedInjectionModule.kt Maven / Gradle / Ivy
package com.squareup.inject.assisted.dagger2.processor
import com.squareup.inject.assisted.processor.assistedInjectFactoryName
import com.squareup.inject.assisted.processor.internal.rawClassName
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import javax.lang.model.element.Modifier.ABSTRACT
import javax.lang.model.element.Modifier.PRIVATE
private val MODULE = ClassName.get("dagger", "Module")
private val BINDS = ClassName.get("dagger", "Binds")
data class AssistedInjectionModule(
val moduleName: ClassName,
val targetNameToFactoryName: Map
) {
val generatedType = moduleName.assistedInjectModuleName()
fun brewJava(): TypeSpec {
return TypeSpec.classBuilder(generatedType)
.addAnnotation(MODULE)
.addModifiers(ABSTRACT)
.addMethod(MethodSpec.constructorBuilder()
.addModifiers(PRIVATE)
.build())
.applyEach(targetNameToFactoryName) { targetName, factoryName ->
val rawTargetName = targetName.rawClassName()
addMethod(MethodSpec.methodBuilder(rawTargetName.bindMethodName())
.addAnnotation(BINDS)
.addModifiers(ABSTRACT)
.returns(factoryName)
.addParameter(rawTargetName.assistedInjectFactoryName(), "factory")
.build())
}
.build()
}
}
private fun ClassName.bindMethodName() = "bind_" + reflectionName().replace('.', '_')
fun ClassName.assistedInjectModuleName(): ClassName = peerClass("AssistedInject_" + simpleName())
private inline fun T.applyEach(items: Map, func: T.(K, V) -> Unit): T {
items.forEach { (key, value) -> func(key, value) }
return this
}