Java Code Examples for com.squareup.javapoet.TypeSpec

The following are top voted examples for showing how to use com.squareup.javapoet.TypeSpec. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: smartkey   File: ServiceHandler.java   Source Code and License 7 votes vote down vote up
void addType(String name, String forName, ClassName serviceType, ClassName builderType, String param) {
    MethodSpec.Builder smartMethod = MethodSpec.methodBuilder("to" + Util.capFirstLetter(name)+ AnnotationConstants.SUFFIX_SERVICE_TARGET)
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .returns(builderType)
            .addStatement("return new $T()", builderType);
    smartTargets.addMethod(smartMethod.build());
    TypeSpec.Builder type = TypeSpec.classBuilder(builderType)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .superclass(ParameterizedTypeName.get(ClazzNames.SERVICE_TARGET, (TypeName)builderType));
    MethodSpec.Builder clazz = MethodSpec.methodBuilder("getServiceClass")
            .addModifiers(Modifier.PROTECTED)
            .returns(ParameterizedTypeName.get(ClazzNames.CLAZZ, serviceType))
            .addStatement("return $T.class", serviceType);
    type.addMethod(clazz.build());
    types.put(forName, type);
}
 
Example 2
Project: smartkey   File: ActivityHandler.java   Source Code and License 6 votes vote down vote up
public void addType(TargetDescriptor des) {
    TypeSpec.Builder type = types.get(des.name);
    if (type == null) {
        ClassName activityType = ClassName.bestGuess(des.name);
        ClassName builderName = ClassName.bestGuess(des.name + AnnotationConstants.SUFFIX_ACTIVITY_TARGET);
        addType(des.getSimpleName(), des.name, activityType, builderName, null);
    }
    if (des.filters.isEmpty() || des.filters.get(0).actions.isEmpty()) {
        return;
    }
    for (TargetFilter filter : des.filters) {
        for(String action : filter.actions) {
            if("android.intent.action.MAIN".equals(action))
                continue;
            addGoActivityMethod(des.name,
                    "goWithAction_" + action.replace('.', '_').replace(" ", "").toUpperCase(),
                    action, filter.categories);
            addGoActivityMethod(des.name,
                    "goForResultWithAction_" + action.replace('.', '_').replace(" ", "").toUpperCase(),
                    action, filter.categories);
        }
    }
}
 
Example 3
Project: smartkey   File: ActivityHandler.java   Source Code and License 6 votes vote down vote up
void addGoActivityMethod(String targetClz, String methodName, String action, ArrayList<String> cats) {
    TypeSpec.Builder type = types.get(targetClz);
    MethodSpec.Builder actionMethod = MethodSpec.methodBuilder(methodName)
            .addModifiers(Modifier.PUBLIC)
            .addStatement("$T in = prepare(src)", ClazzNames.INTENT)
            .addStatement("in.setAction(\"" + action + "\")");
    for (String cat : cats) {
        actionMethod.addStatement("in.addCategory(\"" + cat + "\")");
    }
    if(methodName.contains("ForResult")) {
        actionMethod.addParameter(ClazzNames.ACTIVITY, "src")
                .addParameter(ClassName.INT, "reqCode");
        actionMethod.addStatement("realGoForResult(src, in, reqCode)");
    } else {
        actionMethod.addParameter(ClazzNames.CONTEXT, "src");
        actionMethod.addStatement("realGo(src, in)");
    }
    type.addMethod(actionMethod.build());
}
 
Example 4
Project: GitHub   File: GlideGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec overrideGlideWithMethod(
    String packageName, TypeSpec generatedRequestManager, ExecutableElement methodToOverride) {
  ClassName generatedRequestManagerClassName =
      ClassName.get(packageName, generatedRequestManager.name);
  List<? extends VariableElement> parameters = methodToOverride.getParameters();
  Preconditions.checkArgument(
      parameters.size() == 1, "Expected size of 1, but got %s", methodToOverride);
  VariableElement parameter = parameters.iterator().next();
  return MethodSpec.methodBuilder(methodToOverride.getSimpleName().toString())
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addJavadoc(processorUtil.generateSeeMethodJavadoc(methodToOverride))
      .returns(generatedRequestManagerClassName)
      .addParameter(ClassName.get(parameter.asType()), parameter.getSimpleName().toString())
      .addStatement("return ($T) $T.$N($L)",
          generatedRequestManagerClassName, glideType,
          methodToOverride.getSimpleName().toString(),
          parameter.getSimpleName())
      .build();
}
 
Example 5
Project: aws-sdk-java-v2   File: AsyncClientClass.java   Source Code and License 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getAsyncInterface());
    Builder classBuilder = PoetUtils.createClassBuilder(className)
                                    .addAnnotation(SdkInternalApi.class)
                                    .addModifiers(Modifier.FINAL)
                                    .addField(AsyncClientHandler.class, "clientHandler", Modifier.PRIVATE, Modifier.FINAL)
                                    .addField(protocolSpec.protocolFactory(model))
                                    .addSuperinterface(interfaceClass)
                                    .addJavadoc("Internal implementation of {@link $1T}.\n\[email protected] $1T#builder()",
                                                interfaceClass)
                                    .addMethods(operations())
                                    .addMethod(closeMethod())
                                    .addMethods(protocolSpec.additionalMethods())
                                    .addMethod(protocolSpec.initProtocolFactory(model));

    if (model.getCustomizationConfig().getServiceSpecificClientConfigClass() != null) {
        classBuilder.addMethod(constructorWithAdvancedConfiguration());
    } else {
        classBuilder.addMethod(constructor());
    }

    protocolSpec.createErrorResponseHandler().ifPresent(classBuilder::addMethod);

    return classBuilder.build();
}
 
Example 6
Project: GitHub   File: RequestManagerFactoryGenerator.java   Source Code and License 6 votes vote down vote up
TypeSpec generate(String generatedCodePackageName, TypeSpec generatedRequestManagerSpec) {
  return TypeSpec.classBuilder(GENERATED_REQUEST_MANAGER_FACTORY_SIMPLE_NAME)
      .addModifiers(Modifier.FINAL)
      .addSuperinterface(ClassName.get(requestManagerFactoryInterface))
      .addJavadoc("Generated code, do not modify\n")
      .addMethod(
          MethodSpec.methodBuilder("build")
              .addModifiers(Modifier.PUBLIC)
              .addAnnotation(Override.class)
              .returns(requestManagerClassName)
              .addParameter(ClassName.get(glideType), "glide")
              .addParameter(ClassName.get(lifecycleType), "lifecycle")
              .addParameter(ClassName.get(requestManagerTreeNodeType), "treeNode")
              .addStatement(
                  "return new $T(glide, lifecycle, treeNode)",
                  ClassName.get(generatedCodePackageName, generatedRequestManagerSpec.name))
              .build()
      )
      .build();
}
 
Example 7
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec generateAsMethod(String generatedCodePackageName, TypeSpec requestBuilder) {
  TypeVariableName resourceType = TypeVariableName.get("ResourceType");
  ParameterizedTypeName classOfResouceType = ParameterizedTypeName
      .get(ClassName.get(Class.class), resourceType);

  ClassName generatedRequestBuilderClassName =
      ClassName.get(generatedCodePackageName, requestBuilder.name);

  ParameterizedTypeName requestBuilderOfResourceType = ParameterizedTypeName
      .get(generatedRequestBuilderClassName, resourceType);

  return MethodSpec.methodBuilder("as")
      .addModifiers(Modifier.PUBLIC)
      .addAnnotation(Override.class)
      .addTypeVariable(TypeVariableName.get("ResourceType"))
      .addParameter(classOfResouceType, "resourceClass")
      .returns(requestBuilderOfResourceType)
      .addStatement("return new $T<>(glide, this, resourceClass)",
          this.generatedRequestBuilderClassName)
      .build();
}
 
Example 8
Project: GitHub   File: IndexerGenerator.java   Source Code and License 6 votes vote down vote up
TypeSpec generate(List<TypeElement> types) {
  List<TypeElement> modules =  new ArrayList<>();
  List<TypeElement> extensions = new ArrayList<>();
  for (TypeElement element : types) {
    if (processorUtil.isExtension(element)) {
      extensions.add(element);
    } else if (processorUtil.isLibraryGlideModule(element)) {
      modules.add(element);
    } else {
      throw new IllegalArgumentException("Unrecognized type: " + element);
    }
  }
  if (!modules.isEmpty() && !extensions.isEmpty()) {
    throw new IllegalArgumentException("Given both modules and extensions, expected one or the "
        + "other. Modules: " + modules + " Extensions: " + extensions);
  }
  if (!modules.isEmpty()) {
    return generate(types, GlideModule.class);
  } else {
    return generate(types, GlideExtension.class);
  }
}
 
Example 9
Project: GitHub   File: IndexerGenerator.java   Source Code and License 6 votes vote down vote up
private static TypeSpec generate(List<TypeElement> libraryModules,
    Class<? extends Annotation> annotation) {
  AnnotationSpec.Builder annotationBuilder =
      AnnotationSpec.builder(Index.class);

  String value = getAnnotationValue(annotation);
  for (TypeElement childModule : libraryModules) {
    annotationBuilder.addMember(value, "$S", ClassName.get(childModule).toString());
  }

  String indexerName = INDEXER_NAME_PREFIX + annotation.getSimpleName() + "_";
  for (TypeElement element : libraryModules) {
    indexerName += element.getQualifiedName().toString().replace(".", "_");
    indexerName += "_";
  }
  indexerName = indexerName.substring(0, indexerName.length() - 1);

  return TypeSpec.classBuilder(indexerName)
      .addAnnotation(annotationBuilder.build())
      .addModifiers(Modifier.PUBLIC)
      .build();
}
 
Example 10
Project: easy-plugins   File: PluginProviderInterfaceFileGenerator.java   Source Code and License 6 votes vote down vote up
@Override
public void generate(UserMarkerAnnotation marker, ProcessorOutputCollection into) {
    TypeName providerTypeName = marker.getServiceInterfaceTypeName();
    TypeSpec.Builder typeBuilder = TypeSpec.interfaceBuilder(marker.getServiceInterfaceProviderName())
            .addModifiers(Modifier.PUBLIC)
            .addMethod(
                    Util.publicAbstractMethod(GET_NAME_METHOD_NAME, STRING_TYPE_NAME)
                            .build())
            .addMethod(
                    Util.publicAbstractMethod(CREATE_NEW_METHOD_NAME, providerTypeName)
                            .build())
            .addMethod(
                    Util.publicAbstractMethod(CREATE_NEW_WITH_CONFIG_METHOD_NAME, providerTypeName)
                            .addParameter(CONFIG_TYPE_NAME, CONFIG_ARG_NAME)
                            .build());

    for (EasyPluginPlugin plugin : Util.getPluginLoader()) {
        plugin.updatePluginProviderInterface(typeBuilder, marker);
    }

    TypeSpec type = typeBuilder.build();

    into.putType(marker.getOutputPackage(elements), type);
}
 
Example 11
Project: Kickback   File: KickbackBoxGenerator.java   Source Code and License 6 votes vote down vote up
public TypeSpec generate() {
    return TypeSpec.classBuilder(getClassName())
            .addJavadoc("Generated by Kickback. (https://github.com/skydoves/Kickback).\n")
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(LifecycleObserver.class)
            .addFields(getKickbackFields())
            .addMethods(getSetterMethodSpecs())
            .addMethods(getGetterMethodSpecs())
            .addMethods(getFreeMethodSpecs())
            .addMethod(getBoxNameSpec())
            .addMethods(getElementNameListSpecs())
            .addMethod(getFreeAllSpec())
            .addMethod(setLifecycleObserverSpec())
            .addMethod(getLifecycleObserverSpec())
            .build();
}
 
Example 12
Project: GitHub   File: GlideGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec overrideGlideWithMethod(
    String packageName, TypeSpec generatedRequestManager, ExecutableElement methodToOverride) {
  ClassName generatedRequestManagerClassName =
      ClassName.get(packageName, generatedRequestManager.name);
  List<? extends VariableElement> parameters = methodToOverride.getParameters();
  Preconditions.checkArgument(
      parameters.size() == 1, "Expected size of 1, but got %s", methodToOverride);
  VariableElement parameter = parameters.iterator().next();
  return MethodSpec.methodBuilder(methodToOverride.getSimpleName().toString())
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addJavadoc(processorUtil.generateSeeMethodJavadoc(methodToOverride))
      .returns(generatedRequestManagerClassName)
      .addParameter(ClassName.get(parameter.asType()), parameter.getSimpleName().toString())
      .addStatement("return ($T) $T.$N($L)",
          generatedRequestManagerClassName, glideType,
          methodToOverride.getSimpleName().toString(),
          parameter.getSimpleName())
      .build();
}
 
Example 13
Project: shortbread   File: CodeGenerator.java   Source Code and License 6 votes vote down vote up
void generate() {
    TypeSpec shortbread = TypeSpec.classBuilder("ShortbreadGenerated")
            .addAnnotation(AnnotationSpec.builder(suppressLint)
                    .addMember("value", "$S", "NewApi")
                    .addMember("value", "$S", "ResourceType")
                    .build())
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(createShortcuts())
            .addMethod(callMethodShortcut())
            .build();

    JavaFile javaFile = JavaFile.builder("shortbread", shortbread)
            .indent("    ")
            .build();

    try {
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec generateAsMethod(String generatedCodePackageName, TypeSpec requestBuilder) {
  TypeVariableName resourceType = TypeVariableName.get("ResourceType");
  ParameterizedTypeName classOfResouceType = ParameterizedTypeName
      .get(ClassName.get(Class.class), resourceType);

  ClassName generatedRequestBuilderClassName =
      ClassName.get(generatedCodePackageName, requestBuilder.name);

  ParameterizedTypeName requestBuilderOfResourceType = ParameterizedTypeName
      .get(generatedRequestBuilderClassName, resourceType);

  return MethodSpec.methodBuilder("as")
      .addModifiers(Modifier.PUBLIC)
      .addAnnotation(Override.class)
      .addTypeVariable(TypeVariableName.get("ResourceType"))
      .addParameter(classOfResouceType, "resourceClass")
      .addAnnotation(AnnotationSpec.builder(CHECK_RESULT_CLASS_NAME).build())
      .returns(requestBuilderOfResourceType)
      .addStatement("return new $T<>(glide, this, resourceClass, context)",
          this.generatedRequestBuilderClassName)
      .build();
}
 
Example 15
Project: aws-sdk-java-v2   File: AwsServiceBaseRequestSpec.java   Source Code and License 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder builder = TypeSpec.classBuilder(className())
            .addAnnotation(PoetUtils.GENERATED)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .superclass(ClassName.get(AwsRequest.class))
            .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PROTECTED)
                    .addParameter(className().nestedClass("Builder"), "builder")
                    .addStatement("super(builder)")
                    .build())
            .addMethod(MethodSpec.methodBuilder("toBuilder")
                    .addAnnotation(Override.class)
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .returns(className().nestedClass("Builder"))
                    .build())
            .addType(builderInterfaceSpec())
            .addType(builderImplSpec());
    return builder.build();
}
 
Example 16
Project: Barricade   File: CodeGenerator.java   Source Code and License 6 votes vote down vote up
private static TypeSpec generateEndpointsResponsesInnerClass(String endpoint,
    List<BarricadeResponse> responses) {
  TypeSpec.Builder classBuilder =
      classBuilder(StringUtils.toCamelCase(endpoint)).addModifiers(PUBLIC, STATIC, FINAL);
  int count = 0;
  for (BarricadeResponse response : responses) {
    FieldSpec valuesField = FieldSpec.builder(int.class,
        StringUtils.removeAllSpecialCharactersAndExtensions(response.responseFileName).toUpperCase())
        .addModifiers(PUBLIC, STATIC, FINAL)
        .initializer("$L", count)
        .build();
    classBuilder.addField(valuesField);
    count++;
  }
  return classBuilder.build();
}
 
Example 17
Project: DaggerAutoInject   File: DaggerAutoInjectProcessor.java   Source Code and License 6 votes vote down vote up
private void constructActivityModule() {
    final TypeSpec.Builder builder = TypeSpec.classBuilder(Constants.ACTIVITY_MODULE)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .addAnnotation(Constants.DAGGER_MODULE);

    for (ActivityHolder activityHolder : activityHolders.values()) {
        builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_CONTRIBUTE + activityHolder.className)
                .addAnnotation(Constants.DAGGER_ANDROID_ANNOTATION)
                .addModifiers(Modifier.ABSTRACT)
                .returns(activityHolder.classNameComplete)
                .build()
        );
    }

    final TypeSpec newClass = builder.build();
    final JavaFile javaFile = JavaFile.builder(Constants.PACKAGE_NAME, newClass).build();

    try {
        javaFile.writeTo(System.out);
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: auto-adapter   File: ViewHolderFactoryGenerator.java   Source Code and License 6 votes vote down vote up
private void addFields(final TypeSpec.Builder classBuilder) {
    FieldSpec.Builder viewIdsField = FieldSpec.builder(int[].class, "viewIds", Modifier.PRIVATE, Modifier.STATIC,
            Modifier.FINAL);
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    for (Integer id : viewIds) {
        sb.append(id).append(",");
    }

    if (viewIds.size() > 0) {
        sb.deleteCharAt(sb.length() - 1);
    }

    sb.append("}");
    viewIdsField.initializer(CodeBlock.of(sb.toString()));
    classBuilder.addField(viewIdsField.build());

}
 
Example 19
Project: autoproxy   File: CommonClassGenerator.java   Source Code and License 6 votes vote down vote up
@NonNull
protected TypeSpec.Builder createClass(@NonNull final FieldSpec... members) {
    final TypeSpec.Builder builder = TypeSpec.classBuilder("Proxy_" + type.flatClassName)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);

    // TODO: mimic annotations of the super type

    if (ElementKind.INTERFACE == type.element.getKind()) {
        builder.addSuperinterface(superType);
    } else if (ElementKind.CLASS == type.element.getKind()) {
        builder.superclass(superType);
    } else {
        final String message = "Unsupported data type: " + type.element.getKind() + ", " + type.elementType;
        errors.write(message + "\n");

        throw new UnsupportedOperationException(message);
    }

    for (final FieldSpec member : members) {
        builder.addField(member);
    }

    return builder;
}
 
Example 20
Project: autoproxy   File: CommonClassGenerator.java   Source Code and License 6 votes vote down vote up
/** */
protected void createMethods(@NonNull final TypeSpec.Builder classSpec) throws Exception {
    // compose methods
    RuntimeException runtimeError = null;
    for (final Element method : type.methods) {
        if (!(method instanceof Symbol.MethodSymbol)) {
            final String message = "Unexpected method type: " + method.getClass().getSimpleName();
            errors.write(message + "\n");

            runtimeError = new UnsupportedOperationException(message);
            continue;
        }

        classSpec.addMethod(createMethod((Symbol.MethodSymbol) method).build());
    }

    // if were detected exception, throw it
    if (null != runtimeError) {
        throw runtimeError;
    }
}
 
Example 21
Project: RxRetroJsoup   File: RetroJsoupProcessor.java   Source Code and License 6 votes vote down vote up
public void construct(JsoupModelHolder modelHolder) {

        final TypeSpec.Builder builder = TypeSpec.classBuilder(modelHolder.className + Constants.PARSER)
                .addModifiers(Modifier.PUBLIC);

        for (JsoupModelFieldHolder field : modelHolder.fields) {
            builder.addMethod(MethodSpec.methodBuilder(field.name.replace("-","_").replace(" ","_"))
                    .addModifiers(Modifier.PUBLIC)
                    .returns(TypeName.VOID)
                    .addParameter(modelHolder.classNameComplete, "item")
                    .addParameter(TypeName.get(String.class), "value")
                    .addStatement("item.$L = value", field.name)
                    .build());
        }

        final TypeSpec newClass = builder.build();

        final JavaFile javaFile = JavaFile.builder(modelHolder.classNameComplete.packageName(), newClass).build();

        try {
            javaFile.writeTo(System.out);
            javaFile.writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 22
Project: flowr   File: DeepLinkAnnotationCompiler.java   Source Code and License 6 votes vote down vote up
/**
 * Generate a new deep link handler implementation class with the specified package name,
 * class name and the constructor body.
 *
 * @param packageName        the name of the package to use for the generated class.
 * @param className          the name to be used for the implementation class.
 * @param constructorBuilder the constructor body builder for the class.
 */
private void generateDeepLinkHandler(String packageName, String className,
                                     MethodSpec.Builder constructorBuilder) {
    TypeSpec classObject = getClassObject(className)
            .addMethod(constructorBuilder.build())
            .build();

    JavaFile javaFile = JavaFile.builder(packageName, classObject)
            .build();

    try {
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 23
Project: aws-sdk-java-v2   File: EnumClass.java   Source Code and License 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    Builder enumBuilder = createEnumBuilder(className)
        .addField(String.class, VALUE, Modifier.PRIVATE, Modifier.FINAL)
        .addMethod(toStringBuilder().addStatement("return $T.valueOf($N)", String.class, VALUE).build())
        .addMethod(fromValueSpec())
        .addMethod(knownValuesSpec())
        .addMethod(createConstructor());

    addDeprecated(enumBuilder::addAnnotation, shape);
    addJavadoc(enumBuilder::addJavadoc, shape);

    shape.getEnums().forEach(
        e -> enumBuilder.addEnumConstant(e.getName(), TypeSpec.anonymousClassBuilder("$S", e.getValue()).build())
    );
    enumBuilder.addEnumConstant(UNKNOWN_TO_SDK_VERSION, TypeSpec.anonymousClassBuilder("null").build());

    return enumBuilder.build();
}
 
Example 24
Project: data-mediator   File: TypeAdapterInsertDelegate.java   Source Code and License 5 votes vote down vote up
@Override
public void addClassAnnotation(TypeSpec.Builder typeBuilder) {
    if(!getClassInfo().isGenerateJsonAdapter() || !GlobalConfig.getInstance().isJsonAdapterEnabled()){
        return ;
    }
    ClassName cn_type_adapter = ClassName.get(getClassInfo().getPackageName(),
            Util.getTypeAdapterName(getClassInfo().getDirectParentInterfaceName()));
    typeBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get(PKG_GSON_ANNO, SN_GSON_JSON_ADAPTER))
            .addMember("value", "$T.class", cn_type_adapter)
            .build());
}
 
Example 25
Project: json2java4idea   File: ClassBuilder.java   Source Code and License 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public TypeSpec build(@Nonnull String name) {
    final TypeSpec.Builder classBuilder = TypeSpec.classBuilder(name);
    buildAnnotations().forEach(classBuilder::addAnnotation);
    buildModifiers().forEach(classBuilder::addModifiers);
    buildSuperClass().ifPresent(classBuilder::superclass);
    buildInterfaces().forEach(classBuilder::addSuperinterface);
    buildFields().forEach(classBuilder::addField);
    buildMethods().forEach(classBuilder::addMethod);
    buildInnerTypes().forEach(classBuilder::addType);
    return classBuilder.build();
}
 
Example 26
Project: GankReader   File: OnceClickProcessor.java   Source Code and License 5 votes vote down vote up
private void createJavaFile(ProxyInfo proxyInfo, TypeSpec typeSpec) {
    JavaFile javaFile = JavaFile.builder(proxyInfo.getPackageName(), typeSpec).build();
    try {
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 27
Project: RIBs   File: InteractorTestGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public void generate(InteractorAnnotatedClass annotatedInteractor) throws IOException {
  if (annotatedInteractor.isCodeGenerated()) {
    return;
  }

  String interactorTestBaseClassName =
      Constants.INTERACTOR_TEST_CREATOR_PREFIX
          + annotatedInteractor.getRootName()
          + Constants.INTERACTOR_TEST_CREATOR_SUFFIX;

  MethodSpec constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build();

  MethodSpec createInteractor = createMethodSpec(annotatedInteractor);

  TypeSpec testBaseClass =
      TypeSpec.classBuilder(interactorTestBaseClassName)
          .addMethod(constructor)
          .addMethod(createInteractor)
          .addModifiers(Modifier.PUBLIC)
          .build();

  String packageName = CompilerUtils.packageNameOf(annotatedInteractor.getTypeElement());
  JavaFile.builder(packageName, testBaseClass)
      .build()
      .writeTo(getProcessingEnvironment().getFiler());

  annotatedInteractor.setCodeGenerated(true);
}
 
Example 28
Project: GitHub   File: ExtensionProcessor.java   Source Code and License 5 votes vote down vote up
boolean processExtensions(Set<? extends TypeElement> set, RoundEnvironment env) {
  List<TypeElement> elements = processorUtil.getElementsFor(GlideExtension.class, env);
  processorUtil.debugLog("Processing types : " + elements);
  for (TypeElement typeElement : elements) {
    GlideExtensionValidator.validateExtension(typeElement);
    processorUtil.debugLog("Processing elements: " + typeElement.getEnclosedElements());
  }

  if (elements.isEmpty()) {
    return false;
  }
  TypeSpec spec = indexerGenerator.generate(elements);
  processorUtil.writeIndexer(spec);
  return true;
}
 
Example 29
Project: D-Router   File: RouterTableGenerator.java   Source Code and License 5 votes vote down vote up
private TypeSpec getRouterTableClassTypeSpec(FieldSpec tableFieldSpec, MethodSpec initTableMethodSpec, MethodSpec queryTableMethodSpec, MethodSpec constructorMethodSpec, MethodSpec addRouterMethodSpec) {
    return TypeSpec.classBuilder(Constants.ROUTER_TABLE_CLASS_NAME)
            .addModifiers(Modifier.PUBLIC)
            .addField(tableFieldSpec)
            .addMethod(initTableMethodSpec)
            .addMethod(queryTableMethodSpec)
            .addMethod(constructorMethodSpec)
            .addMethod(addRouterMethodSpec)
            .build();
}
 
Example 30
Project: jso-builder   File: SerializerGenerator.java   Source Code and License 5 votes vote down vote up
public TypeSpec createSerializer(ClassName className) {
    return TypeSpec.classBuilder(className)
            .addModifiers(Modifier.STATIC)
            .superclass(className.peerClass("Serializer"))
            .addMethod(createToJSONMethod())
            .addMethod(createIsJsObject())
            .addMethod(createWriteJSONMethod())
            .addMethod(createWriteValueMethod())
            .build();
}
 
Example 31
Project: json2java4idea   File: SuppressWarningsAnnotationPolicyTest.java   Source Code and License 5 votes vote down vote up
@Test
public void applyShouldAddGeneratedAnnotation() throws Exception {
    // setup
    final TypeSpec.Builder builder = TypeSpec.classBuilder("Test");

    // exercise
    underTest.apply(builder);

    // verify
    assertThat(builder.build())
            .hasName("Test")
            .hasAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
                    .addMember("value", "$S", "all")
                    .build());
}
 
Example 32
Project: aws-sdk-java-v2   File: AwsServiceBaseRequestSpec.java   Source Code and License 5 votes vote down vote up
private TypeSpec builderImplSpec() {
    return TypeSpec.classBuilder("BuilderImpl")
            .addModifiers(Modifier.PROTECTED, Modifier.STATIC, Modifier.ABSTRACT)
            .addSuperinterface(className().nestedClass("Builder"))
            .superclass(ClassName.get(AwsRequest.class).nestedClass("BuilderImpl"))
            .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PROTECTED)
                    .build())
            .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PROTECTED)
                    .addParameter(className(), "request")
                    .addStatement("super(request)")
                    .build())
            .build();
}
 
Example 33
Project: resourceprovider   File: RpCodeGenerator.java   Source Code and License 5 votes vote down vote up
TypeSpec generateDimensionProviderClass() {
    MethodSpec constructor = MethodSpec.constructorBuilder()
                                       .addModifiers(PUBLIC)
                                       .addParameter(contextClassName, "context")
                                       .addStatement("this.context = context")
                                       .build();

    TypeSpec.Builder classBuilder = classBuilder("DimensionProvider")
            .addModifiers(PUBLIC)
            .addField(contextField)
            .addMethod(constructor)
            .addAnnotation(suppressLint);


    for (String var : rClassDimenVars) {
        try {
            classBuilder.addMethod(MethodSpec.methodBuilder("get" + getterSuffix(var) + "PixelSize")
                                             .addModifiers(Modifier.PUBLIC)
                                             .returns(INT)
                                             .addStatement("return context.getResources().getDimensionPixelSize(R.dimen." + var + ")")
                                             .varargs(false)
                                             .addJavadoc("Returns the dimension R.dimen." + var + " in pixels")
                                             .build());
        } catch (IllegalArgumentException e) {
            System.out.println("\n\nResourceProvider Compiler Error: " + e.getMessage() + ".\n\nUnable to generate API for R.dimen." + var + "\n\n") ;
        }

    }

    return classBuilder.build();
}
 
Example 34
Project: auto-nav   File: NavProcessor.java   Source Code and License 5 votes vote down vote up
private void createNavigator(Set<ActivityIntentModel> activityModels) {

        TypeSpec.Builder navigatorBuilder = TypeSpec.classBuilder(navigatorClassName)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL);

        for (ActivityIntentModel model : activityModels) {
            createActivityIntent(model);

            /**
             *         public static MainActivityIntent toMainActivity(Context context){
             *             MainActivityIntent intent = new MainActivityIntent(context, "com.com.MainActivity");
             *             return intent;
             *         }
             */

            ClassName returnType = ClassName.get(model.getPackageName(), model.getIntentClzName());
            MethodSpec.Builder methodSpecBuilder = MethodSpec
                    .methodBuilder(METHOD_PREFIX + model.getClzName());
            methodSpecBuilder.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .addParameter(classContext, "context")
                    .returns(ClassName.get(model.getPackageName(), model.getIntentClzName()))
                    .addStatement("$T intent = new $T($L,$S)", returnType, returnType, "context", model.getQualifiedName())
                    .addStatement("return intent");

            navigatorBuilder.addMethod(methodSpecBuilder.build());
        }

        addPreGoListener(navigatorBuilder);


        try {
            JavaFile.builder(navigatorPackageName, navigatorBuilder.build()).build().writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
 
Example 35
Project: aws-sdk-java-v2   File: MemberCopierSpec.java   Source Code and License 5 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder builder = TypeSpec.classBuilder(className())
            .addModifiers(Modifier.FINAL)
            .addAnnotation(PoetUtils.GENERATED)
            .addMethod(copyMethod());

    if (serviceModelCopiers.requiresBuilderCopier(memberModel)) {
        builder.addMethod(builderCopyMethod());
    }

    return builder.build();
}
 
Example 36
Project: jso-builder   File: JSOBuilderProcessor.java   Source Code and License 5 votes vote down vote up
private TypeSpec createJsonInterface() {
    return TypeSpec.classBuilder("JSON")
            .addModifiers(Modifier.STATIC, Modifier.FINAL)
            .addAnnotation(AnnotationSpec.builder(ClassNames.JSINTEROP_JSTYPE)
                    .addMember("isNative", "true")
                    .addMember("namespace", "$T.GLOBAL", ClassNames.JSINTEROP_JSPACKAGE)
                    .addMember("name", "$S", "JSON")
                    .build())
            .addMethod(MethodSpec.methodBuilder("stringify")
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.NATIVE)
                    .addParameter(Object.class, "object")
                    .returns(String.class)
                    .build())
            .build();
}
 
Example 37
Project: domino   File: PresenterCommandSourceWriter.java   Source Code and License 5 votes vote down vote up
@Override
public String write() throws IOException {
    TypeSpec contributionRequest = DominoTypeBuilder.build(className, PresenterCommandProcessor.class)
            .addAnnotation(Command.class)
            .superclass(ParameterizedTypeName.get(ClassName.get(PresenterCommand.class), presenterType))
            .build();

    StringBuilder asString = new StringBuilder();
    JavaFile.builder(targetPackage, contributionRequest).skipJavaLangImports(true).build().writeTo(asString);
    return asString.toString();
}
 
Example 38
Project: easy-plugins   File: ProcessorOutputCollection.java   Source Code and License 5 votes vote down vote up
public void writeContents(Filer filer) {
    for (Map.Entry<String, Set<TypeSpec>> newTypes : outputClasses.entrySet()) {
        for (TypeSpec type : newTypes.getValue()) {
            type = type.toBuilder().addJavadoc(Constants.AUTOGEN_COMMENT).build();
            writeFile(filer,
                    JavaFile.builder(newTypes.getKey(), type).build());
        }
    }

    for (Map.Entry<String, Set<String>> service : serviceProviders.entrySet()) {
        Util.writeMetaInfServices(service.getKey(), service.getValue(), filer);
    }
}
 
Example 39
Project: GitHub   File: GlideGenerator.java   Source Code and License 5 votes vote down vote up
private List<MethodSpec> generateOverridesForGlideMethods(
    final String generatedCodePackageName, final TypeSpec generatedRequestManager) {
  return Lists.transform(discoverGlideMethodsToOverride(),
      new Function<ExecutableElement, MethodSpec>() {
        @Override
        public MethodSpec apply(ExecutableElement input) {
          if (isGlideWithMethod(input)) {
            return overrideGlideWithMethod(
                generatedCodePackageName, generatedRequestManager, input);
          } else {
            return overrideGlideStaticMethod(input);
          }
        }
      });
}
 
Example 40
Project: GitHub   File: ProcessorUtil.java   Source Code and License 5 votes vote down vote up
void writeClass(String packageName, TypeSpec clazz) {
  try {
    debugLog("Writing class:\n" + clazz);
    JavaFile.builder(packageName, clazz).build().writeTo(processingEnv.getFiler());
  } catch (Throwable e) {
    throw new RuntimeException(e);
  }
}
 
Example 41
Project: GitHub   File: ExtensionProcessor.java   Source Code and License 5 votes vote down vote up
boolean processExtensions(RoundEnvironment env) {
  List<TypeElement> elements = processorUtil.getElementsFor(GlideExtension.class, env);
  processorUtil.debugLog("Processing types : " + elements);
  for (TypeElement typeElement : elements) {
    extensionValidator.validateExtension(typeElement);
    processorUtil.debugLog("Processing elements: " + typeElement.getEnclosedElements());
  }

  if (elements.isEmpty()) {
    return false;
  }
  TypeSpec spec = indexerGenerator.generate(elements);
  processorUtil.writeIndexer(spec);
  return true;
}
 
Example 42
Project: arez   File: AutorunDescriptor.java   Source Code and License 5 votes vote down vote up
/**
 * Build any fields required by
 */
void buildFields( @Nonnull final TypeSpec.Builder builder )
{
  final FieldSpec.Builder field =
    FieldSpec.builder( GeneratorUtil.OBSERVER_CLASSNAME,
                       GeneratorUtil.FIELD_PREFIX + getName(),
                       Modifier.FINAL,
                       Modifier.PRIVATE ).
      addAnnotation( GeneratorUtil.NONNULL_CLASSNAME );
  builder.addField( field.build() );
}
 
Example 43
Project: Jerkoff   File: MainTest.java   Source Code and License 5 votes vote down vote up
@Test
@Ignore
public void test() throws IOException {
    Properties prop = PropertiesUtils.loadProperties("META-INF/generator.properties");
    File sourcePath = new File(prop.getProperty(PropertiesUtils.TARGET_FOLDER));
    Class<?> clazz = Integer.class;
    MongoDBDao mongo = new MongoDBDaoImpl(prop);
    PojoCreator creator = new PojoCreatorImpl(prop, mongo);
    LOG.info("Creating tests for public methods of " + clazz.getSimpleName());
    TypeSpec classTest = creator.getTypeSpec(clazz);
    creator.writeJavaFile(sourcePath, clazz, classTest);
}
 
Example 44
Project: jdoocsoup   File: JDoocsSoupAnnotationProcessor.java   Source Code and License 5 votes vote down vote up
private void createJavaFile(String packageName, TypeSpec typeSpec) {
    try {
        JavaFile javaFile = JavaFile.builder(packageName, typeSpec)
                .build();
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException ex) {
        processingEnv.getMessager()
                .printMessage(Diagnostic.Kind.ERROR, "It was not possible to generate java files due to an error: \n" + ex.getMessage());
    }
}
 
Example 45
Project: konohana   File: StoreWriter.java   Source Code and License 5 votes vote down vote up
@NonNull
private TypeSpec buildTypeSpec() {
    return TypeSpec.classBuilder(storeDefinition.getStoreClassName())
            .addSuperinterface(storeDefinition.getInterfaceName())
            .addModifiers(Modifier.PUBLIC)
            .addField(buildPrefsField())
            .addField(buildSubjectField())
            .addField(buildListenerField())
            .addMethod(buildConstructor())
            .addMethods(StoreMethods.build(storeDefinition))
            .build();
}
 
Example 46
Project: json2java4idea   File: JavaBuilderImpl.java   Source Code and License 5 votes vote down vote up
@Nonnull
@Override
public String build(@Nonnull String packageName, @Nonnull TypeSpec typeSpec) throws JavaBuildException {
    return JavaFile.builder(packageName, typeSpec)
            .indent(INDENT)
            .skipJavaLangImports(true)
            .build()
            .toString();
}
 
Example 47
Project: domino   File: RegisterViewsMethodWriter.java   Source Code and License 5 votes vote down vote up
@Override
protected void registerItem(ViewEntry entry, MethodSpec.Builder methodBuilder) {
    MethodSpec makeMethod = MethodSpec.methodBuilder("make")
            .addModifiers(Modifier.PROTECTED)
            .addAnnotation(Override.class)
            .returns(View.class)
            .addStatement("return new $T()", ClassName.bestGuess(entry.view))
            .build();
    TypeSpec lazyLoaderType = TypeSpec.anonymousClassBuilder("$T.class.getCanonicalName()",
            ClassName.bestGuess(entry.presenter))
            .superclass(LazyViewLoader.class)
            .addMethod(makeMethod)
            .build();
    methodBuilder.addStatement("registry.registerView($L)", lazyLoaderType);
}
 
Example 48
Project: auto-adapter   File: ViewBinderGenerator.java   Source Code and License 5 votes vote down vote up
private TypeSpec.Builder createClassBuilder(final TypeElement model, final ClassName viewBinderClassName) {
    TypeName modelType = ParameterizedTypeName.get(model.asType());
    ParameterizedTypeName viewHolderBinderTypeName = ParameterizedTypeName.get(VIEW_BINDER_NAME, modelType);

    return TypeSpec.classBuilder(viewBinderClassName).addModifiers(Modifier.FINAL).addSuperinterface(
            viewHolderBinderTypeName);
}
 
Example 49
Project: arez   File: AutorunDescriptor.java   Source Code and License 5 votes vote down vote up
void buildMethods( @Nonnull final TypeSpec.Builder builder )
  throws ArezProcessorException
{
  builder.addMethod( buildAutorun() );
  if ( null != _refMethod )
  {
    builder.addMethod( buildObserverRefMethod() );
  }
}
 
Example 50
Project: aws-sdk-java-v2   File: AwsServiceBaseResponseSpec.java   Source Code and License 5 votes vote down vote up
private TypeSpec builderInterfaceSpec() {
    return TypeSpec.interfaceBuilder("Builder")
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(ClassName.get(AwsResponse.class).nestedClass("Builder"))

            .addMethod(MethodSpec.methodBuilder("build")
                    .addAnnotation(Override.class)
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .returns(className())
                    .build())
            .build();
}
 
Example 51
Project: raml-java-tools   File: TypeSpecMatchers.java   Source Code and License 5 votes vote down vote up
public static Matcher<TypeSpec> methods(Matcher<Iterable<? extends MethodSpec>> memberMatcher) {

    return new FeatureMatcher<TypeSpec, Iterable<? extends MethodSpec>>(memberMatcher, "method", "method") {

      @Override
      protected Iterable<? extends MethodSpec> featureValueOf(TypeSpec actual) {

        return actual.methodSpecs;
      }
    };
  }
 
Example 52
Project: dataenum   File: DataEnumProcessor.java   Source Code and License 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
  Filer filer = processingEnv.getFiler();
  Messager messager = processingEnv.getMessager();

  for (Element element : roundEnvironment.getElementsAnnotatedWith(DataEnum.class)) {
    try {

      Spec spec = SpecParser.parse(element, processingEnv);
      if (spec == null) {
        continue;
      }

      OutputSpec outputSpec = OutputSpecFactory.create(spec);
      TypeSpec outputTypeSpec = SpecTypeFactory.create(outputSpec);

      JavaFile.Builder javaFileBuilder =
          JavaFile.builder(outputSpec.outputClass().packageName(), outputTypeSpec);
      if (needsCheckNotNull(spec)) {
        javaFileBuilder.addStaticImport(DataenumUtils.class, "checkNotNull");
      }
      if (needsNullSafeEquals(spec)) {
        javaFileBuilder.addStaticImport(DataenumUtils.class, "equal");
      }

      JavaFile javaFile = javaFileBuilder.build();
      javaFile.writeTo(filer);

    } catch (IOException | ParserException e) {
      messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
    }
  }

  return false;
}
 
Example 53
Project: LifecycleAware   File: MethodWrapperGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public TypeSpec defineClass() {
    return TypeSpec.classBuilder(producer.getClassName(annotatedElement))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addSuperinterface(LifecycleAwareObserver.class)
            .addField(TypeName.get(annotatedElement.asType()), FIELD_NAME, Modifier.PRIVATE)
            .build();
}
 
Example 54
Project: aws-sdk-java-v2   File: SyncClientBuilderClass.java   Source Code and License 5 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder builder =
            PoetUtils.createClassBuilder(builderClassName)
                     .addAnnotation(SdkInternalApi.class)
                     .addModifiers(Modifier.FINAL)
                     .superclass(ParameterizedTypeName.get(builderBaseClassName, builderInterfaceName, clientInterfaceName))
                     .addSuperinterface(builderInterfaceName)
                     .addJavadoc("Internal implementation of {@link $T}.", builderInterfaceName)
                     .addMethod(buildClientMethod());

    return builder.build();
}
 
Example 55
Project: RNLearn_Project1   File: ReactPropertyProcessor.java   Source Code and License 5 votes vote down vote up
private void generateCode(ClassInfo classInfo, List<PropertyInfo> properties)
    throws IOException, ReactPropertyException {
  MethodSpec getMethods = MethodSpec.methodBuilder("getProperties")
      .addModifiers(PUBLIC)
      .addAnnotation(Override.class)
      .addParameter(PROPERTY_MAP_TYPE, "props")
      .returns(TypeName.VOID)
      .addCode(generateGetProperties(properties))
      .build();

  TypeName superType = getSuperType(classInfo);
  ClassName className = classInfo.mClassName;

  String holderClassName =
      getClassName((TypeElement) classInfo.mElement, className.packageName()) + "$$PropsSetter";
  TypeSpec holderClass = TypeSpec.classBuilder(holderClassName)
      .addSuperinterface(superType)
      .addModifiers(PUBLIC)
      .addMethod(generateSetPropertySpec(classInfo, properties))
      .addMethod(getMethods)
      .build();

  JavaFile javaFile = JavaFile.builder(className.packageName(), holderClass)
      .addFileComment("Generated by " + getClass().getName())
      .build();

  javaFile.writeTo(mFiler);
}
 
Example 56
Project: DDComponentForAndroid   File: RouterProcessor.java   Source Code and License 5 votes vote down vote up
/**
 * generate HostUIRouter.java
 */
private void generateRouterImpl() {

    String claName = RouteUtils.genHostUIRouterClass(host);

    //pkg
    String pkg = claName.substring(0, claName.lastIndexOf("."));
    //simpleName
    String cn = claName.substring(claName.lastIndexOf(".") + 1);
    // superClassName
    ClassName superClass = ClassName.get(elements.getTypeElement(BASECOMPROUTER));

    MethodSpec initHostMethod = generateInitHostMethod();
    MethodSpec initMapMethod = generateInitMapMethod();

    try {
        JavaFile.builder(pkg, TypeSpec.classBuilder(cn)
                .addModifiers(PUBLIC)
                .superclass(superClass)
                .addMethod(initHostMethod)
                .addMethod(initMapMethod)
                .build()
        ).build().writeTo(mFiler);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 57
Project: PreferenceRoom   File: PreferenceRoomProcessor.java   Source Code and License 5 votes vote down vote up
private void generateProcessComponent(PreferenceComponentAnnotatedClass annotatedClass) {
    try {
        TypeSpec annotatedClazz = (new PreferenceComponentGenerator(annotatedClass, annotatedEntityMap)).generate();
        JavaFile.builder(annotatedClass.packageName, annotatedClazz).build().writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        // ignore >.<
    }
}
 
Example 58
Project: java-code-templates   File: DeferredTypeSpecBuilder.java   Source Code and License 5 votes vote down vote up
public TypeSpec build() {
	return wrappedBuilder.addTypes(
			deferredBuilders.stream()
				.map(DeferredTypeSpecBuilder::build)
				.collect(toList()))
			.build();
}
 
Example 59
Project: autoproxy   File: CommonClassGenerator.java   Source Code and License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public boolean compose(@NonNull final Filer filer) {
    try {
        // compose class
        final FieldSpec[] members = createMembers();
        final TypeSpec.Builder classSpec = createClass(members);

        // constructor and predicate
        classSpec.addMethod(createConstructor().build());
        classSpec.addMethod(createPredicate().build());

        // auto-generate method proxy calls
        createMethods(classSpec);

        // if any after call annotation found in class/methods
        if (afterCalls.get()) {
            classSpec.addMethod(createAfterCall().build());
        }

        // save class to disk
        final JavaFile javaFile = JavaFile.builder(type.packageName.toString(), classSpec.build()).build();
        javaFile.writeTo(filer);

    } catch (final Throwable ignored) {
        ignored.printStackTrace(new PrintWriter(errors));
        return false;
    }

    return true;
}
 
Example 60
Project: auto-adapter   File: ViewHolderFactoryGenerator.java   Source Code and License 5 votes vote down vote up
private void addCreateMethod(final TypeSpec.Builder viewHolderFactoryClass, final TypeElement model,
                             final CodeBlock codeBlock, final ClassName viewHolderClassName) {

    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(viewHolderClassName,
            TypeName.get(model.asType()));

    MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create").returns(parameterizedTypeName)
            .addParameter(AndroidClassNames.VIEW_GROUP, "parent")
            .addCode(codeBlock).addModifiers(Modifier.PUBLIC);

    viewHolderFactoryClass.addMethod(createMethod.build());
}