com.squareup.javapoet.TypeSpec Java Examples

The following examples show how to use com.squareup.javapoet.TypeSpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FinalRClassBuilder.java    From Briefness with Apache License 2.0 6 votes vote down vote up
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable,
                                     ClassName annotation) {
  String fieldName = variable.getNameAsString();
  String fieldValue = variable.getInitializer()
      .map(Node::toString)
      .orElseThrow(
          () -> new IllegalStateException("Field " + fieldName + " missing initializer"));
  FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName)
      .addModifiers(PUBLIC, STATIC, FINAL)
      .initializer(fieldValue);

  if (annotation != null) {
    fieldSpecBuilder.addAnnotation(annotation);
  }

  resourceType.addField(fieldSpecBuilder.build());
}
 
Example #2
Source File: SolidityFunctionWrapperTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildFuncNameConstants() throws Exception {
    AbiDefinition functionDefinition = new AbiDefinition(
            false,
            Arrays.asList(
                    new AbiDefinition.NamedType("param", "uint8")),
            "functionName",
            Collections.emptyList(),
            "function",
            true);
    TypeSpec.Builder builder = TypeSpec.classBuilder("testClass");

    builder.addFields(solidityFunctionWrapper
            .buildFuncNameConstants(Collections.singletonList(functionDefinition)));


    //CHECKSTYLE:OFF
    String expected =
            "class testClass {\n" +
                    "  public static final java.lang.String FUNC_FUNCTIONNAME = \"functionName\";\n" +
                    "}\n";
    //CHECKSTYLE:ON


    assertThat(builder.build().toString(), is(expected));
}
 
Example #3
Source File: DaggerAutoInjectProcessor.java    From DaggerAutoInject with Apache License 2.0 6 votes vote down vote up
private void constructFragmentModule() {
    final TypeSpec.Builder builder = TypeSpec.classBuilder(Constants.FRAGMENT_MODULE)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .addAnnotation(Constants.DAGGER_MODULE);

    for (FragmentHolder fragmentHolder : fragmentHolders.values()) {
        builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_CONTRIBUTE + fragmentHolder.className)
                .addAnnotation(Constants.DAGGER_ANDROID_ANNOTATION)
                .addModifiers(Modifier.ABSTRACT)
                .returns(fragmentHolder.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 #4
Source File: PassCreate.java    From soabase-halva with Apache License 2.0 6 votes vote down vote up
private void addTypeAliasType(TypeSpec.Builder builder, ClassName aliasClassName, DeclaredType parentType)
{
    TypeName parentTypeName = ClassName.get(parentType);
    ClassName typeAliasTypeName = ClassName.get(TypeAliasType.class);
    ClassName anyTypeName = ClassName.get(AnyType.class);
    ParameterizedTypeName typeName = ParameterizedTypeName.get(typeAliasTypeName, parentTypeName, aliasClassName);

    CodeBlock codeBlock = CodeBlock.builder()
        .add(
            "new $T<>(new $T<$T>(){}, new $T<$T>(){}, $L::$L)",
            typeAliasTypeName,
            anyTypeName,
            parentTypeName,
            anyTypeName,
            aliasClassName,
            aliasClassName.simpleName(),
            aliasClassName.simpleName()
            )
        .build();

    FieldSpec fieldSpec = FieldSpec.builder(typeName, "TypeAliasType", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
        .initializer(codeBlock)
        .build();
    builder.addField(fieldSpec);
}
 
Example #5
Source File: InterceptorProcessor.java    From EasyRouter with Apache License 2.0 6 votes vote down vote up
private TypeSpec getInterceptorInitializer(Set<? extends Element> interceptorElements) throws ClassNotFoundException {
    ClassName interceptor = ClassName.get("com.android.easyrouter.intercept", "IInterceptor");
    ClassName list = ClassName.get("java.util", "List");
    TypeName interceptorList = ParameterizedTypeName.get(list, interceptor);

    MethodSpec.Builder routerInitBuilder = MethodSpec
            .methodBuilder("initModuleInterceptor")
            .returns(interceptorList)
            .addModifiers(Modifier.PUBLIC)
            .addModifiers(Modifier.STATIC);
    routerInitBuilder.addStatement("List<IInterceptor> list = new java.util.ArrayList()");
    for (Element element : interceptorElements) {
        routerInitBuilder.addStatement("list.add(new $T())",
                ClassName.get((TypeElement) element));
    }
    routerInitBuilder.addStatement("return list");

    return TypeSpec.classBuilder(CompilerConstant.AutoCreateInterceptorPrefix + moduleName)
            .addModifiers(Modifier.PUBLIC)
            .addMethod(routerInitBuilder.build())
            .build();
}
 
Example #6
Source File: GenerateSystemCode.java    From Intimate with Apache License 2.0 6 votes vote down vote up
public JavaFile generate() {
    MethodSpec.Builder construction = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addException(ClassNotFoundException.class)
            .addParameter(Object.class, "object");
    if (model.getTargetName().fullName.contains("$") || model.isNeedForName()) {
        construction.addStatement("this.mObject = object")
                .addStatement("this.mClass = Class.forName($S)", model.getTargetName().fullName);
    } else {
        construction.addStatement("this.mObject = object")
                .addStatement("this.mClass = $N.class", model.getTargetName().fullName);
    }

    TypeSpec.Builder implClass = TypeSpec.classBuilder(model.getImplClassName())
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(model.getInterfaceName().typeName)
            .addMethod(construction.build())
            .addField(Object.class, "mObject")
            .addField(Class.class, "mClass");

    generateFiled(implClass, model.getFieldList());
    generateMethod(implClass, model.getMethodList());

    return JavaFile.builder(INTIMATE_PACKAGE, implClass.build()).build();
}
 
Example #7
Source File: ApplicationGenerator.java    From nalu with Apache License 2.0 6 votes vote down vote up
private void generateLoadDefaultsRoutes(TypeSpec.Builder typeSpec,
                                        MetaModel metaModel) {
  typeSpec.addMethod(MethodSpec.methodBuilder("loadDefaultRoutes")
                               .addModifiers(Modifier.PUBLIC)
                               .addAnnotation(Override.class)
                               .addStatement("$T sb01 = new $T()",
                                             ClassName.get(StringBuilder.class),
                                             ClassName.get(StringBuilder.class))
                               .addStatement("this.startRoute = $S",
                                             metaModel.getStartRoute())
                               .addStatement("sb01.append(\"found startRoute >>$L<<\")",
                                             metaModel.getStartRoute())
                               .addStatement("$T.get().logDetailed(sb01.toString(), 2)",
                                             ClassName.get(ClientLogger.class))
                               .addStatement("sb01.setLength(0)")
                               .addStatement("$T.get().logDetailed(sb01.toString(), 2)",
                                             ClassName.get(ClientLogger.class))
                               .build());
}
 
Example #8
Source File: DatabaseHelperCreator.java    From AirData with MIT License 6 votes vote down vote up
private MethodSpec generateDeleteByIdMethod(TypeSpec.Builder typeSpecBuilder) {
    MethodSpec.Builder saveMethodBuidler = MethodSpec.methodBuilder("delete")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(TypeName.INT)
            .addParameter(ClassName.get(Object.class), "bean");

    for (TableInfo table : tables) {

        String daoField = table.getDaoClassName().replace("$$", "").toLowerCase();

        MethodSpec methodSpec = MethodSpec.methodBuilder("delete")
                .addModifiers(Modifier.PUBLIC)
                .returns(TypeName.INT)
                .addParameter(ClassName.get(table.getPackageName(), table.getClassName()), "bean")
                .addStatement("return $L.delete(bean)", daoField)
                .build();
        typeSpecBuilder.addMethod(methodSpec);

        saveMethodBuidler.addStatement("if(bean instanceof $L) return delete(($L)bean)", table.getClassName(), table.getClassName());
    }

    saveMethodBuidler.addStatement("return 0");
    return saveMethodBuidler.build();
}
 
Example #9
Source File: NodeFactoryGenerator.java    From caffeine with Apache License 2.0 6 votes vote down vote up
private void writeJavaFile() throws IOException {
  String header = Resources.toString(Resources.getResource("license.txt"), UTF_8).trim();
  JavaFile.builder(getClass().getPackage().getName(), nodeFactory.build())
      .addFileComment(header, Year.now(timeZone))
      .indent("  ")
      .build()
      .writeTo(directory);

  for (TypeSpec node : nodeTypes) {
    JavaFile.builder(getClass().getPackage().getName(), node)
            .addFileComment(header, Year.now(timeZone))
            .indent("  ")
            .build()
            .writeTo(directory);
  }
}
 
Example #10
Source File: FactoryGenerator.java    From toothpick with Apache License 2.0 6 votes vote down vote up
private void emitSuperMemberInjectorFieldIfNeeded(TypeSpec.Builder scopeMemberTypeSpec) {
  if (constructorInjectionTarget.superClassThatNeedsMemberInjection != null) {
    ClassName superTypeThatNeedsInjection =
        ClassName.get(constructorInjectionTarget.superClassThatNeedsMemberInjection);
    ParameterizedTypeName memberInjectorSuperParameterizedTypeName =
        ParameterizedTypeName.get(
            ClassName.get(MemberInjector.class), superTypeThatNeedsInjection);
    FieldSpec.Builder superMemberInjectorField =
        FieldSpec.builder(
                memberInjectorSuperParameterizedTypeName, "memberInjector", Modifier.PRIVATE)
            // TODO use proper typing here
            .initializer(
                "new $L__MemberInjector()",
                getGeneratedFQNClassName(
                    constructorInjectionTarget.superClassThatNeedsMemberInjection));
    scopeMemberTypeSpec.addField(superMemberInjectorField.build());
  }
}
 
Example #11
Source File: SolidityFunctionWrapperTest.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildFuncNameConstants() throws Exception {
    AbiDefinition functionDefinition =
            new AbiDefinition(
                    false,
                    Arrays.asList(new AbiDefinition.NamedType("param", "uint8")),
                    "functionName",
                    Collections.emptyList(),
                    "function",
                    true);
    TypeSpec.Builder builder = TypeSpec.classBuilder("testClass");

    builder.addFields(
            solidityFunctionWrapper.buildFuncNameConstants(
                    Collections.singletonList(functionDefinition)));

    String expected =
            "class testClass {\n"
                    + "  public static final java.lang.String FUNC_FUNCTIONNAME = \"functionName\";\n"
                    + "}\n";

    assertEquals(builder.build().toString(), (expected));
}
 
Example #12
Source File: RegisterRouterProcessor.java    From Android-Router with MIT License 6 votes vote down vote up
private void generateRouterRule(List<RouterModule> moduleList) {
	System.out.println("moduleList = " + Arrays.toString(moduleList.toArray()));
	try {
		String pkgName = CompilerHelper.ROUTER_MANAGER_TABLE_PKN;
		String className = CompilerHelper.ROUTER_MANAGER_TABLE_CLASS_NAME + moduleList.get(0).module;
		String methodName = CompilerHelper.ROUTER_MANAGER_TABLE_METHOD_NAME;
		MethodSpec registerRouter = computeRouterTable(methodName, moduleList);

		TypeSpec routerManger = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).addMethod(registerRouter).build();
		JavaFile javaFile = JavaFile.builder(pkgName, routerManger).build();
		javaFile.writeTo(mFiler);
	} catch (IOException e) {
		e.printStackTrace();
	}

}
 
Example #13
Source File: AsyncClientInterface.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder result = PoetUtils.createInterfaceBuilder(className);

    result.addSuperinterface(SdkClient.class)
          .addField(FieldSpec.builder(String.class, "SERVICE_NAME")
                             .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                             .initializer("$S", model.getMetadata().getSigningName())
                             .build());

    PoetUtils.addJavadoc(result::addJavadoc, getJavadoc());

    if (!model.getCustomizationConfig().isExcludeClientCreateMethod()) {
        result.addMethod(create());
    }

    result.addMethod(builder())
          .addMethods(operationsAndSimpleMethods());

    if (model.getCustomizationConfig().getUtilitiesMethod() != null) {
        result.addMethod(utilitiesMethod());
    }

    return result.build();
}
 
Example #14
Source File: SerializableAutoValueExtension.java    From auto with Apache License 2.0 6 votes vote down vote up
private String generate() {
  ClassName superclass = ClassName.get(context.packageName(), classToExtend);
  Optional<AnnotationSpec> generatedAnnotationSpec =
      GeneratedAnnotationSpecs.generatedAnnotationSpec(
          context.processingEnvironment().getElementUtils(),
          context.processingEnvironment().getSourceVersion(),
          SerializableAutoValueExtension.class);

  TypeSpec.Builder subclass =
      TypeSpec.classBuilder(className)
          .superclass(getClassTypeName(superclass, typeVariableNames))
          .addTypeVariables(typeVariableNames)
          .addModifiers(isFinal ? Modifier.FINAL : Modifier.ABSTRACT)
          .addMethod(constructor())
          .addMethod(writeReplace())
          .addType(proxyGenerator.generate());
  generatedAnnotationSpec.ifPresent(subclass::addAnnotation);

  return JavaFile.builder(context.packageName(), subclass.build()).build().toString();
}
 
Example #15
Source File: Generator.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private TypeSpec newServiceInterfaceSpec(final State state, final boolean blocking) {
    final String name = context.deconflictJavaTypeName((blocking ? Blocking : "") +
            sanitizeIdentifier(state.serviceProto.getName(), false) + "Service");

    final TypeSpec.Builder interfaceSpecBuilder = interfaceBuilder(name)
            .addModifiers(PUBLIC)
            .addSuperinterface(blocking ? BlockingGrpcService : GrpcService);

    state.serviceRpcInterfaces.stream()
            .filter(e -> e.blocking == blocking)
            .map(e -> e.className)
            .forEach(interfaceSpecBuilder::addSuperinterface);

    return interfaceSpecBuilder.build();
}
 
Example #16
Source File: CrnkProcessor.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private void addQueryConstructors(TypeElement resourceType, TypeSpec.Builder typeBuilder) {
    String pathClassName = getSimpleName(resourceType.getSimpleName().toString(), false);

    MethodSpec.Builder defaultConstructor = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addStatement(String.format("super(%s.class, new %s())", resourceType.getQualifiedName(), pathClassName));
    typeBuilder.addMethod(defaultConstructor.build());
}
 
Example #17
Source File: StructureWriter.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
private TypeSpec mapperFunction(@NonNull CodeBlock functionBody) {
  return TypeSpec
      .anonymousClassBuilder("")
      .addSuperinterface(ParameterizedTypeName.get(MAPPER, structureElementTypeName))
      .addMethod(MethodSpec.methodBuilder("apply")
          .addAnnotation(Override.class)
          .addModifiers(PUBLIC)
          .addParameter(CURSOR, "cursor")
          .returns(structureElementTypeName)
          .addCode(functionBody)
          .build())
      .build();
}
 
Example #18
Source File: HTCodeGenerator.java    From ht-universalrouter-android with MIT License 5 votes vote down vote up
public static TypeSpec generateHTRouterHandlerClass(String packageName, List<HTAnnotatedClass> classes) {
        TypeSpec.Builder builder = TypeSpec.interfaceBuilder(ROUTER_HANDLER_CLASS_NAME)
                .addModifiers(PUBLIC);
        MethodSpec.Builder handleMethod = MethodSpec.methodBuilder("handleRoute")
                .addModifiers(PUBLIC, ABSTRACT)
                .returns(boolean.class)
                .addParameter(ClassName.get("android.content", "Context"), "context")
                .addParameter(ClassName.get(packageName, "HTRouterHandlerParams"), "routerParams");
//                .addParameter(String.class, "url")
//                .addParameter(ClassName.get("android.content", "Intent"), "intent")
//                .addParameter(int.class, "type");
        builder.addMethod(handleMethod.build());
        return builder.build();
    }
 
Example #19
Source File: Utils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 构建 Reset 方法
 * @param classBuilder DevEnvironment 类构建对象
 */
public static void builderResetMethod(final TypeSpec.Builder classBuilder) {
    StringBuilder varBuilder = new StringBuilder();
    Iterator<Map.Entry<String, List<String>>> iterator = sModuleNameMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, List<String>> entry = iterator.next();
        // Module 名
        String moduleName = entry.getKey();
        // 拼接变量设置为 null
        varBuilder.append(String.format("    %s = null;\n", VAR_SELECT_ENVIRONMENT + moduleName));
    }

    // 构建 reset 实现代码
    CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
    codeBlockBuilder.add("if ($N != null && $N($N)) {\n", VAR_CONTEXT, METHOD_DELETE_STORAGE_DIR, VAR_CONTEXT);
    codeBlockBuilder.add(varBuilder.toString());
    codeBlockBuilder.add("    return true;\n");
    codeBlockBuilder.add("}\n");

    // public static final void reset() {}
    MethodSpec resetMethod = MethodSpec
            .methodBuilder(METHOD_RESET)
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
            .addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
            .addCode(codeBlockBuilder.build())
            .returns(Boolean.class)
            .addStatement("return false")
            .addJavadoc("重置操作\n")
            .addJavadoc("<p>Reset Operating\n")
            .addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
            .addJavadoc("@return {@code true} success, {@code false} fail\n")
            .build();
    classBuilder.addMethod(resetMethod);
}
 
Example #20
Source File: InvokingMessageProcessor.java    From SmartEventBus with Apache License 2.0 5 votes vote down vote up
private String generateEventInterfaceClass(List<EventInfo> events, String originalPackageName, String originalClassName) {
    String interfaceName = generateClassName(originalClassName);
    TypeSpec.Builder builder = TypeSpec.interfaceBuilder(interfaceName)
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(IEventsDefine.class)
            .addJavadoc("Auto generate code, do not modify!!!");
    for (EventInfo event : events) {
        ClassName lebClassName = ClassName.get(LEB_PACKAGE_NAME, LEB_CLASS_NAME);
        ClassName obsClassName = lebClassName.nestedClass(LEB_OBSERVER_CLASS_NAME);
        TypeName returnType;
        String eventTypeStr = event.getType();
        if (eventTypeStr == null || eventTypeStr.length() == 0) {
            returnType = ParameterizedTypeName.get(obsClassName, ClassName.get(Object.class));
        } else {
            Type eventType = getType(eventTypeStr);
            if (eventType != null) {
                returnType = ParameterizedTypeName.get(obsClassName, ClassName.get(eventType));
            } else {
                returnType = ParameterizedTypeName.get(obsClassName, TypeVariableName.get(eventTypeStr));
            }
        }
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(event.getName())
                .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                .returns(returnType);
        builder.addMethod(methodBuilder.build());
    }
    TypeSpec typeSpec = builder.build();
    String packageName = originalPackageName + GEN_PKG;
    try {
        JavaFile.builder(packageName, typeSpec)
                .build()
                .writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String className = packageName + "." + interfaceName;
    System.out.println(TAG + "generateEventInterfaceClass: " + className);
    return className;
}
 
Example #21
Source File: JavaGeneratorTest.java    From raptor with Apache License 2.0 5 votes vote down vote up
private void writeJavaFile(ClassName javaTypeName, TypeSpec typeSpec, Location location)
        throws IOException {
    JavaFile.Builder builder = JavaFile.builder(javaTypeName.packageName(), typeSpec)
            .addFileComment("$L", "Code generated by Wire protocol buffer compiler, do not edit.");
    if (location != null) {
        builder.addFileComment("\nSource file: $L", location);
    }
    JavaFile javaFile = builder.build();
    try {
        javaFile.writeTo(new File(GENERATED_SOURCE_DIR));
    } catch (IOException e) {
        throw new IOException("Failed to write " + javaFile.packageName + "."
                + javaFile.typeSpec.name + " to " + GENERATED_SOURCE_DIR, e);
    }
}
 
Example #22
Source File: TypeSpecMatchers.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
public static Matcher<TypeSpec> fields(Matcher<Iterable<? extends FieldSpec>> memberMatcher) {

        return new FeatureMatcher<TypeSpec, Iterable<? extends FieldSpec>>(memberMatcher, "field", "field") {

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

                return actual.fieldSpecs;
            }
        };
    }
 
Example #23
Source File: PersistWriter.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
@Override
public void writeHandler(TypeSpec.Builder classBuilder) {
  final MethodSpec internalPersist = internalPersist();
  final MethodSpec internalPersistIgnoringNull = internalPersistIgnoringNull();
  classBuilder
      .addMethod(internalPersistIgnoringNull)
      .addMethod(internalPersist())
      .addType(persist(internalPersist, internalPersistIgnoringNull))
      .addType(bulkPersist());
}
 
Example #24
Source File: FlapProcessor.java    From Flap with Apache License 2.0 5 votes vote down vote up
/**
 * 处理 AutoRegister 注解,把需要自动注册的组件处理一下。
 *
 * @param roundEnvironment
 * @param typeElement
 */
private void processComponentProxyManager(final RoundEnvironment roundEnvironment, final TypeElement typeElement) {

    if (!autoRegisterFactories) {
        return;
    }
    List<ClassName> factories = new ArrayList<>();

    Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(AutoRegister.class);

    for (final Element element : elements) {
        TypeElement flapItemFactory = (TypeElement) element;
        ClassName factoryClass = ClassName.get(flapItemFactory);
        factories.add(factoryClass);
    }

    TypeSpec manager = TypeSpec.classBuilder("ComponentAutoRegister")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addAnnotation(CLASS_KEEP)
            .addMethod(createInjectMethod(factories))
            .build();

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

}
 
Example #25
Source File: NodeComposer.java    From spring-data-jpa-entity-graph with MIT License 5 votes vote down vote up
public NodeComposer() {
  rootType = TypeVariableName.get("R");

  FieldSpec rootField =
      FieldSpec.builder(rootType, Constants.PATH_SEPARATOR)
          .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
          .build();

  ParameterizedTypeName listOfString = ParameterizedTypeName.get(List.class, String.class);

  FieldSpec pathField =
      FieldSpec.builder(listOfString, "path")
          .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
          .build();

  MethodSpec constructor =
      MethodSpec.constructorBuilder()
          .addModifiers(Modifier.PUBLIC)
          .addParameter(rootType, "root")
          .addParameter(listOfString, "path")
          .addStatement("this.____ = root")
          .addStatement("this.path = path")
          .build();

  typeSpecBuilder =
      TypeSpec.classBuilder(SIMPLE_NAME)
          .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
          .addTypeVariable(rootType)
          .addField(rootField)
          .addField(pathField)
          .addMethod(constructor);
}
 
Example #26
Source File: ApiImplProcessor.java    From ApiManager with Apache License 2.0 5 votes vote down vote up
private TypeSpec buildClass(ApiContract<ClassName> apiNameContract) {
    return TypeSpec.classBuilder(apiNameContract.getApi().simpleName() + ApiConstants.SEPARATOR + ApiConstants.CONTRACT)
            .addSuperinterface(ClassName.get(elements.getTypeElement(ApiConstants.INTERFACE_NAME_CONTRACT)))
            .addModifiers(Modifier.PUBLIC)
            .addMethod(buildMethod(apiNameContract))
            .build();
}
 
Example #27
Source File: AutoValueWithExtension.java    From auto-value-with with Apache License 2.0 5 votes vote down vote up
@Override
public String generateClass(
        Context context, String className, String classToExtend, boolean isFinal) {
    TypeSpec subclass =
            newTypeSpecBuilder(context, className, classToExtend, isFinal)
                    .addMethods(generateWithMethods(context))
                    .build();

    return JavaFile.builder(context.packageName(), subclass).build().toString();
}
 
Example #28
Source File: MethodRouterGenerator.java    From componentrouter with Apache License 2.0 5 votes vote down vote up
/**
 *
 * is() 方法
 * @param builder
 * @param routeType
 */
private void addIsForMethod(TypeSpec.Builder builder, ClassName routeType) {
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_IS)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC)
            .returns(boolean.class)
            .addParameter(Object.class, "obj")
            .addCode("return $T.class==obj.getClass();\n", routeType);
    builder.addMethod(methodBuilder.build());
}
 
Example #29
Source File: MethodRouterGenerator.java    From componentrouter with Apache License 2.0 5 votes vote down vote up
/**
 * 添加构造方法
 * @param builder
 * @param routeType
 */
private void addConstructorMethod(TypeSpec.Builder builder, ClassName routeType) {
    MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder()
            .addParameter(routeType, "obj")
            .addModifiers(Modifier.PUBLIC)
            .addCode(PROXY_FIELD_NAME + "=obj;\n");
    builder.addMethod(methodBuilder.build());
}
 
Example #30
Source File: BaseDecorator.java    From EasyMVP with Apache License 2.0 5 votes vote down vote up
protected void addMethods(TypeSpec.Builder result) {
    result.addMethod(getInitializeMethod())
            .addMethod(getInitializeMethodWithFactory())
            .addMethod(getAttachViewMethod())
            .addMethod(getDetachViewMethod())
            .addMethod(getDestroyMethod())
            .addMethod(getLoaderManagerMethod(getLoaderMethodSignature()));
}