Java Code Examples for com.squareup.javapoet.TypeSpec.classBuilder()

The following are Jave code examples for showing how to use classBuilder() of the com.squareup.javapoet.TypeSpec class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: greycat   File: ConstantGenerator.java   View Source Code Vote up 6 votes
private static JavaFile generateGlobalConstant(String packageName, Constant[] globalConstants) {
    TypeSpec.Builder javaClass = TypeSpec.classBuilder(CONSTANT_CLASS_NAME);
    javaClass.addModifiers(PUBLIC, FINAL);
    for (Constant constant : globalConstants) {
        String value = constant.value();
        if (constant.type().equals("Task") && value != null) {
            value = "greycat.Tasks.newTask().parse(\"" + value.replaceAll("\"", "'").trim() + "\",null);";
        } else if (constant.type().equals("String") && value != null) {
            value = "\""+value+"\"";
        }
        FieldSpec.Builder field = FieldSpec.builder(clazz(constant.type()), constant.name())
                .addModifiers(PUBLIC, STATIC);
        if (value != null) {
            field.addModifiers(FINAL).initializer(value);
        }
        javaClass.addField(field.build());
    }
    return JavaFile.builder(packageName, javaClass.build()).build();
}
 
Example 2
Project: react4j   File: Generator.java   View Source Code Vote up 6 votes
@Nonnull
private static TypeSpec buildDaggerModule( @Nonnull final ComponentDescriptor descriptor )
{
  final TypeSpec.Builder builder = TypeSpec.classBuilder( "DaggerModule" );

  builder.addModifiers( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL );
  builder.addAnnotation( ClassName.bestGuess( Constants.DAGGER_MODULE_CLASSNAME ) );

  final MethodSpec.Builder method =
    MethodSpec.methodBuilder( "provideComponent" ).
      addAnnotation( ClassName.bestGuess( Constants.DAGGER_PROVIDES_CLASSNAME ) ).
      addModifiers( Modifier.STATIC ).
      addParameter( descriptor.getClassNameToConstruct(), "component", Modifier.FINAL ).
      returns( COMPONENT_CLASSNAME ).
      addStatement( "return component" );
  builder.addMethod( method.build() );

  return builder.build();
}
 
Example 3
Project: Jerkoff   File: PojoCreatorImpl.java   View Source Code Vote up 6 votes
/**
 * genera classe di test per clazz
 * 
 * @param clazz
 * @param prop
 * @param mongo
 * @return
 */
@Override
public TypeSpec getTypeSpec(Class<?> clazz) {
	Builder classTestBuilder = TypeSpec.classBuilder(clazz.getSimpleName() + TEST);
	ClassName superClass = ClassName.get(
			PropertiesUtils.getRequiredProperty(prop, PropertiesUtils.TEST_BASE_PACKAGE),
			PropertiesUtils.getRequiredProperty(prop, PropertiesUtils.TEST_BASE_CLASS));
	classTestBuilder.superclass(superClass);
	classTestBuilder.addJavadoc("@author \n");
	classTestBuilder.addModifiers(Modifier.PUBLIC);
	AnnotationSpec.Builder annSpecBuilder = AnnotationSpec.builder(Generated.class);
	annSpecBuilder.addMember("value", "\"it.fratta.jerkoff.Generator\"");
	annSpecBuilder.addMember("date", "\"" + Calendar.getInstance().getTime().toString() + "\"");
	AnnotationSpec annGenSpec = annSpecBuilder.build();
	classTestBuilder.addAnnotation(annGenSpec);
	/*
	 * for spring test
	 */
	// FieldSpec.Builder spec = FieldSpec.builder(clazz,
	// getNewInstanceOfNoParameters(clazz), Modifier.PRIVATE);
	// spec.addAnnotation(Autowired.class);
	// classTestBuilder.addField(spec.build());
	addClassMethodsToBuilder(classTestBuilder, clazz);
	return classTestBuilder.build();
}
 
Example 4
Project: javabard   File: ValueClassSpec.java   View Source Code Vote up 6 votes
public TypeSpec.Builder build() {
    TypeSpec.Builder tsb = TypeSpec.classBuilder(name);
    for (Map.Entry<String, Class<?>> entry : nameTypeMap.entrySet()) {
        FieldSpec field = FieldSpec.builder(
                ClassName.get(entry.getValue()), entry.getKey(), Modifier.PRIVATE)
                .build();
        tsb.addField(field);
    }
    if (getter) {
        tsb = GetterSpec.forType(tsb).build();
    }
    if (setter) {
        tsb = SetterSpec.forType(tsb).build();
    }
    if (builder) {
        tsb = BuilderSpec.forType(packageName, tsb).build();
    }
    return tsb;
}
 
Example 5
Project: auto   File: NoOpProcessor.java   View Source Code Vote up 6 votes
private JavaFile process(EnrichedTypeElement element) throws AbortProcessingException {
  TypeSpec.Builder builder = TypeSpec.classBuilder(element.getClassName(NO_OP_SUFFIX));

  if (element.getAnnotation(AutoNoOp.class).instance()) {
    builder
        .addField(createInstanceField(element))
        .addMethod(createInstanceMethod(element));
  }

  if (element.isInterface()) {
    builder.addSuperinterface(element.getTypeName());
  } else if (element.isAbstract()) {
    builder.superclass(element.getTypeName());
  } else {
    throw new AbortProcessingException("Cannot generate implementation for final class");
  }

  builder
      .addModifiers(element.getAccessModifier())
      .addTypeVariables(element.getTypeVariables())
      .addMethods(createOverridingMethods(element));

  return JavaFile.builder(element.getPackageName(), builder.build())
      .build();
}
 
Example 6
Project: json2java4idea   File: ClassBuilder.java   View Source Code Vote up 5 votes
@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 7
Project: json2java4idea   File: SuppressWarningsAnnotationPolicyTest.java   View Source Code Vote up 5 votes
@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 8
Project: json2java4idea   File: GeneratedAnnotationPolicyTest.java   View Source Code Vote up 5 votes
@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(Generated.class)
                    .addMember("value", "$S", this.getClass().getCanonicalName())
                    .build());
}
 
Example 9
Project: inspector   File: InspectorFactoryProcessor.java   View Source Code Vote up 4 votes
private TypeSpec createValidatorFactory(List<TypeElement> elements,
    String packageName,
    String factoryName) {
  TypeSpec.Builder factory =
      TypeSpec.classBuilder(ClassName.get(packageName, "InspectorFactory_" + factoryName));
  factory.addModifiers(PUBLIC, FINAL);
  factory.superclass(ClassName.get(packageName, factoryName));

  ParameterSpec type = TYPE_SPEC;
  ParameterSpec annotations = ANNOTATIONS_SPEC;
  ParameterSpec moshi = INSPECTOR_SPEC;

  MethodSpec.Builder create = MethodSpec.methodBuilder("create")
      .addModifiers(PUBLIC)
      .addAnnotation(Override.class)
      .addParameters(ImmutableSet.of(type, annotations, moshi))
      .returns(FACTORY_RETURN_TYPE_NAME);

  CodeBlock.Builder classes = null;
  CodeBlock.Builder generics = null;

  int numGenerics = 0;
  int numClasses = 0;

  // Avoid providing an adapter for an annotated type.
  create.addStatement("if (!$N.isEmpty()) return null", annotations);

  for (TypeElement element : elements) {
    TypeName elementTypeName = TypeName.get(element.asType());

    if (elementTypeName instanceof ParameterizedTypeName) {
      if (generics == null) {
        generics = CodeBlock.builder()
            .beginControlFlow("if ($N instanceof $T)", type, ParameterizedType.class)
            .addStatement("$T rawType = (($T) $N).getRawType()",
                Type.class,
                ParameterizedType.class,
                type);
      }

      addControlFlowGeneric(generics, elementTypeName, element, numGenerics);
      numGenerics++;
    } else {
      ExecutableElement jsonAdapterMethod = getValidatorMethod(element);
      if (jsonAdapterMethod != null) {
        if (classes == null) {
          classes = CodeBlock.builder();
        }

        addControlFlow(classes, CodeBlock.of("$N", type), elementTypeName, numClasses);
        numClasses++;

        classes.addStatement("return $T.$L($N)",
            element,
            jsonAdapterMethod.getSimpleName(),
            moshi);
      }
    }
  }

  if (generics != null) {
    generics.endControlFlow();
    generics.addStatement("return null");
    generics.endControlFlow();
    create.addCode(generics.build());
  }

  if (classes != null) {
    classes.endControlFlow();
    create.addCode(classes.build());
  }

  create.addStatement("return null");
  factory.addMethod(create.build());
  return factory.build();
}