use of com.squareup.javapoet.TypeSpec.Builder in project tiger by google.
the class NewInjectorGenerator method generateInjectorBuilder.
private void generateInjectorBuilder(ComponentInfo componentInfo, TypeSpec.Builder injectorBuilder) {
TypeSpec.Builder builderBuilder = TypeSpec.classBuilder("Builder").addModifiers(Modifier.PUBLIC, Modifier.STATIC);
ClassName injectorClassName = ClassName.get(topLevelPackageString, getTopLevelInjectorName(componentInfo));
boolean hasParent = componentTree.get(componentInfo) != null;
ClassName parentClassName = null;
// set parent inject methods.
if (hasParent) {
parentClassName = ClassName.get(topLevelPackageString, getTopLevelInjectorName(componentTree.get(componentInfo)));
Utils.addSetMethod(injectorClassName, builderBuilder, parentClassName);
}
/**
* Set module methods. Theoretically, is a passed module is needed by a injector should be
* decided by whether it is needed. Here is just a simpler way. All scoped modules go to
* injector of the same scope. All unscoped modules go to every injector. It is not possible to
* have modules of different scope in a injector. This way the modules created is a superset of
* what are required. But that's fine because null can be passed in for modules not needed. This
* is even unnoticeable when using builder to create injector. The null module is just never
* referenced. Otherwise it is a bug, sadly it is not caught until runtime. This makes it easier
* to create wrapper component defined dagger around core injectors. Anyway, passed module is
* not a good idea and could/should be removed.
*/
List<TypeElement> allNonNullaryCtorModules = new ArrayList<>();
allNonNullaryCtorModules.addAll(nonNullaryCtorModules.get(componentInfo));
allNonNullaryCtorModules.addAll(nonNullaryCtorUnscopedModules);
for (TypeElement m : allNonNullaryCtorModules) {
Utils.addSetMethod(injectorClassName, builderBuilder, (ClassName) ClassName.get(m.asType()));
}
// build() method.
MethodSpec.Builder buildMethodBuilder = MethodSpec.methodBuilder("build").addModifiers(Modifier.PUBLIC).returns(injectorClassName);
StringBuilder returnCodeBuilder = new StringBuilder("return new $T(");
if (hasParent) {
String parentInjectorFieldName = Utils.getSourceCodeName(parentClassName);
returnCodeBuilder.append(parentInjectorFieldName);
if (!allNonNullaryCtorModules.isEmpty()) {
returnCodeBuilder.append(", ");
}
}
if (!allNonNullaryCtorModules.isEmpty()) {
for (TypeElement module : Utils.sortByFullName(allNonNullaryCtorModules)) {
String moduleFiledName = Utils.getSourceCodeName(TypeName.get(module.asType()));
returnCodeBuilder.append(moduleFiledName).append(", ");
}
int size = returnCodeBuilder.length();
returnCodeBuilder.delete(size - 2, size);
}
returnCodeBuilder.append(");");
buildMethodBuilder.addCode(returnCodeBuilder.toString(), injectorClassName);
builderBuilder.addMethod(buildMethodBuilder.build());
injectorBuilder.addType(builderBuilder.build());
}
Aggregations