Java Code Examples for com.squareup.javapoet.JavaFile

The following examples show how to use com.squareup.javapoet.JavaFile. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: grouter-android   Source File: RouterBuildHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static void build(File sourceDir, File jsonDir, String projectName, String scheme, String host) {
    RouterModel routerModel = getRouterModel(jsonDir, projectName, scheme, host, false);
    if (routerModel == null) {
        return;
    }
    try {
        JavaFile activityJavaFile = RouterActivityCodeBuilder.getJavaFile(projectName + "ActivityCenter", routerModel.activityModels);
        JavaFile taskJavaFile = RouterTaskCodeBuilder.getJavaFile(projectName + "TaskCenter", routerModel.taskModels);
        JavaFile componentJavaFile = RouterComponentCodeBuilder.getJavaFile(projectName + "ComponentCenter", routerModel.componentModels);
        JavaFile initializer = RouterAutoInitializerBuilder.getJavaFile(projectName, scheme, host, routerModel);
        // 代理
        RouterDelegateCodeBuilder.buildJavaFile(projectName,projectName + "DelegateCenter", routerModel.delegateModels, sourceDir);

        activityJavaFile.writeTo(sourceDir);
        taskJavaFile.writeTo(sourceDir);
        componentJavaFile.writeTo(sourceDir);
        initializer.writeTo(sourceDir);
    } catch (Throwable e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
 
Example 2
@Override
public void execute() throws MojoFailureException {
    try {
        JavaFile.builder("org.apache.camel.k.loader.yaml", generateJacksonModule())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml", generateReifiers())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml", generateResolver())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
    } catch (IOException e) {
        throw new MojoFailureException(e.getMessage());
    }
}
 
Example 3
@Override
public void execute() throws MojoFailureException {
    try {
        JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasExpression())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasDataFormat())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasLoadBalancerType())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
    } catch (IOException e) {
        throw new MojoFailureException(e.getMessage());
    }
}
 
Example 4
Source Project: auto   Source File: GeneratedAnnotationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (first) {
    TypeSpec.Builder type = TypeSpec.classBuilder("G");
    GeneratedAnnotationSpecs.generatedAnnotationSpec(
            processingEnv.getElementUtils(),
            processingEnv.getSourceVersion(),
            TestProcessor.class)
        .ifPresent(type::addAnnotation);
    JavaFile javaFile = JavaFile.builder("", type.build()).build();
    try {
      javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
    first = false;
  }
  return false;
}
 
Example 5
Source Project: shortbread   Source File: CodeGenerator.java    License: Apache License 2.0 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 6
Source Project: sqlbrite-dao   Source File: ObjectMappableProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate code
 */
private void generateCode() throws IOException {

  for (ObjectMappableAnnotatedClass clazz : annotatedClasses) {

    String packageName = getPackageName(clazz);

    // Generate the mapper class
    String mapperClassName = clazz.getSimpleClassName() + "Mapper";
    TypeSpec mapperClass = TypeSpec.classBuilder(mapperClassName)
        .addJavadoc("Generated class to work with Cursors and ContentValues for $T\n",
            ClassName.get(clazz.getElement()))
        .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
        .addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build())
        .addField(generateRxMappingMethod(clazz))
        .addMethod(generateContentValuesMethod(clazz, mapperClassName, "ContentValuesBuilder"))
        .addType(
            generateContentValuesBuilderClass(clazz, mapperClassName, "ContentValuesBuilder"))
        .build();

    JavaFile.builder(packageName, mapperClass).build().writeTo(filer);
  }
}
 
Example 7
Source Project: motif   Source File: Case1CasesGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  TypeName A = TypeVariableName.get("A");
  TypeName bounds = ParameterizedTypeName.get(ClassName.get(Case1.class), A);
  TypeName t = TypeVariableName.get("T", bounds);
  TypeName clazz = ParameterizedTypeName.get(ClassName.get(Class.class), t);

  Match1MethodSpec case1Match = Match1MethodSpec.builder()
      .withName("case1").withSummaryJavadoc("Matches a case class of one element.\n")
      .addNonMatchParam(clazz, "clazz").withMatchExtractor(Case1FieldExtractor.class, "clazz")
      .withParamA(A, "a").build();

  JavaFile cases1CasesFile = CasesGenerator.newBuilder(
      "com.leacox.motif.cases", "Case1Cases", t)
      .addFileComment(Copyright.COPYRIGHT_NOTICE)
      .addJavadoc("Motif cases for matching a {@link Case1}.\n")
      .addMatch1Method(case1Match)
      .build().generate();

  try {
    cases1CasesFile.writeTo(System.out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 8
Source Project: Akatsuki   Source File: AkatsukiProcessorSourceNameTest.java    License: Apache License 2.0 6 votes vote down vote up
private static GeneratedClassWithName staticInnerClass(String... classes) {
	// maybe (String first, String...more) ?
	if (classes.length == 0)
		throw new IllegalArgumentException("");
	String[] generatedClasses = new String[classes.length];
	TypeSpec.Builder lastBuilder = null;
	for (int i = classes.length - 1; i >= 0; i--) {
		String clazz = classes[i];
		final Builder currentBuilder = TypeSpec.classBuilder(clazz)
				.addModifiers((i == 0 ? Modifier.PUBLIC : Modifier.STATIC))
				.addField(field(STRING_TYPE, clazz.toLowerCase(), Retained.class));
		if (lastBuilder != null) {
			currentBuilder.addType(lastBuilder.build());
		}
		// we generate static inner class names eg A.B -> A$B
		generatedClasses[i] = IntStream.range(0, i + 1).boxed().map(n -> classes[n])
				.collect(Collectors.joining("$"));
		lastBuilder = currentBuilder;
	}
	final JavaFile file = JavaFile.builder(TEST_PACKAGE, lastBuilder.build()).build();
	final JavaFileObject object = JavaFileObjects
			.forSourceString(TEST_PACKAGE + "." + classes[0], file.toString());

	return new GeneratedClassWithName(object, generatedClasses);
}
 
Example 9
Source Project: Moxy   Source File: MvpCompiler.java    License: MIT License 6 votes vote down vote up
private <E extends Element, R> void generateCode(Element element,
                                                 ElementKind kind,
                                                 ElementProcessor<E, R> processor,
                                                 JavaFilesGenerator<R> classGenerator) {
	if (element.getKind() != kind) {
		getMessager().printMessage(Diagnostic.Kind.ERROR, element + " must be " + kind.name());
	}

	//noinspection unchecked
	R result = processor.process((E) element);

	if (result == null) return;

	for (JavaFile file : classGenerator.generate(result)) {
		createSourceFile(file);
	}
}
 
Example 10
Source Project: pocketknife   Source File: BuilderGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public JavaFile generate() {
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
            .addSuperinterface(ClassName.get(classPackage, interfaceName))
            .addModifiers(PUBLIC)
            .addJavadoc(getGeneratedComment(BuilderGenerator.class));

    generateKeys(classBuilder);

    if (contextRequired) {
        classBuilder.addField(ClassName.get(typeUtil.contextType), CONTEXT, PRIVATE, FINAL);
        classBuilder.addMethod(MethodSpec.constructorBuilder()
                .addModifiers(PUBLIC)
                .addParameter(ClassName.get(typeUtil.contextType), CONTEXT)
                .addStatement("this.$N = $N", CONTEXT, CONTEXT)
                .build());
    }

    generateMethods(classBuilder);

    return JavaFile.builder(classPackage, classBuilder.build()).build();
}
 
Example 11
Source Project: greycat   Source File: ConstantGenerator.java    License: Apache License 2.0 6 votes vote down vote up
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 12
Source Project: kaif-android   Source File: RetrofitServiceProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void generateCode(RetrofitServiceInterface retrofitServiceInterface) {

    TypeSpec typeSpec = retrofitServiceInterface.createRetryStaleInterface();

    TypeElement annotatedClassElement = retrofitServiceInterface.getAnnotatedClassElement();
    JavaFile javaFile = JavaFile.builder(elementUtils.getPackageOf(annotatedClassElement)
        .getQualifiedName()
        .toString(), typeSpec).build();
    try {
      JavaFileObject jfo = filer.createSourceFile(retrofitServiceInterface.getQualifiedName());
      try (Writer writer = jfo.openWriter()) {
        javaFile.writeTo(writer);
      }
    } catch (IOException e) {
      error(annotatedClassElement, e.getMessage());
    }
  }
 
Example 13
Source Project: dart   Source File: IntentBuilderGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String brewJava() {
  TypeSpec.Builder intentBuilderTypeBuilder =
      TypeSpec.classBuilder(builderClassName()).addModifiers(Modifier.PUBLIC);

  emitInitialStateGetter(intentBuilderTypeBuilder);
  emitNextStateGetter(intentBuilderTypeBuilder);
  emitExtraDSLStateMachine(intentBuilderTypeBuilder);
  emitResolvedOptionalSequence(intentBuilderTypeBuilder);
  emitInitialState(intentBuilderTypeBuilder);

  //build
  JavaFile javaFile =
      JavaFile.builder(target.classPackage, intentBuilderTypeBuilder.build())
          .addFileComment("Generated code from Henson. Do not modify!")
          .addStaticImport(ActivityClassFinder.class, "getClassDynamically")
          .build();
  return javaFile.toString();
}
 
Example 14
Source Project: motif   Source File: Tuple1CasesGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  TypeName A = TypeVariableName.get("A");
  TypeName t = ParameterizedTypeName.get(ClassName.get(Tuple1.class), A);

  Match1MethodSpec tuple1Match = Match1MethodSpec.builder()
      .withName("tuple1").withSummaryJavadoc("Matches a tuple of 1 element.\n")
      .withMatchExtractor(Tuple1FieldExtractor.class).withParamA(A, "a").build();

  JavaFile tuple1CasesFile = CasesGenerator.newBuilder(
      "com.leacox.motif.cases", "Tuple1Cases", t)
      .addFileComment(Copyright.COPYRIGHT_NOTICE)
      .addJavadoc("Motif cases for matching a {@link Tuple1}.\n")
      .addMatch1Method(tuple1Match)
      .build().generate();

  try {
    tuple1CasesFile.writeTo(System.out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 15
Source Project: pocketknife   Source File: BundleBindingAdapterGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public JavaFile generate() throws IOException {
    TypeVariableName t = TypeVariableName.get("T");
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
            .addTypeVariable(TypeVariableName.get(t.name, ClassName.get(targetType)))
            .addModifiers(PUBLIC)
            .addJavadoc(getGeneratedComment(BundleBindingAdapterGenerator.class));

    if (parentAdapter != null) {
        classBuilder.superclass(ParameterizedTypeName.get(parentAdapter, t));
    } else {
        classBuilder.addSuperinterface(ParameterizedTypeName.get(ClassName.get(BundleBinding.class), t));
    }

    addSaveStateMethod(classBuilder, t);
    addRestoreStateMethod(classBuilder, t);
    addBindingArgumentsMethod(classBuilder, t);

    return JavaFile.builder(classPackage, classBuilder.build()).build();
}
 
Example 16
Source Project: barber   Source File: Barbershop.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates the class code and writes to a new source file.
 *
 * @param filer Annotation filer instance provided by {@link BarberProcessor}
 * @throws IOException
 */
void writeToFiler(Filer filer) throws IOException {
    ClassName targetClassName = ClassName.get(classPackage, targetClass);
    TypeSpec.Builder barberShop = TypeSpec.classBuilder(className)
            .addModifiers(Modifier.PUBLIC)
            .addTypeVariable(TypeVariableName.get("T", targetClassName))
            .addMethod(generateStyleMethod())
            .addMethod(generateCheckParentMethod());

    if (parentBarbershop == null) {
        barberShop.addSuperinterface(ParameterizedTypeName.get(ClassName.get(Barber.IBarbershop.class), TypeVariableName.get("T")));
        barberShop.addField(FieldSpec.builder(WeakHashSet.class, "lastStyledTargets", Modifier.PROTECTED).initializer("new $T()", WeakHashSet.class).build());
    } else {
        barberShop.superclass(ParameterizedTypeName.get(ClassName.bestGuess(parentBarbershop), TypeVariableName.get("T")));
    }

    JavaFile javaFile = JavaFile.builder(classPackage, barberShop.build()).build();
    javaFile.writeTo(filer);
}
 
Example 17
Source Project: motif   Source File: OptionalCasesGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  TypeName T = TypeVariableName.get("T");
  TypeName o = ParameterizedTypeName.get(ClassName.get(Optional.class), T);

  Match0MethodSpec noneMatch = Match0MethodSpec.builder()
      .withName("none").withSummaryJavadoc("Matches an empty {@link Optional}.\n")
      .withMatchExtractor(OptionalNoneFieldExtractor.class).build();

  Match1MethodSpec someMatch = Match1MethodSpec.builder()
      .withName("some").withSummaryJavadoc("Matches a non-empty {@link Optional}.\n")
      .withMatchExtractor(OptionalFieldExtractor.class).withParamA(T, "t").build();

  JavaFile optionalCasesFile =
      CasesGenerator.newBuilder("com.leacox.motif.cases", "OptionalCases", o)
          .addFileComment(Copyright.COPYRIGHT_NOTICE)
          .addJavadoc("Motif cases for matching an {@link Optional}.\n")
          .addMatch0Method(noneMatch)
          .addMatch1Method(someMatch)
          .build().generate();

  try {
    optionalCasesFile.writeTo(System.out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 18
Source Project: zerocell   Source File: ZeroCellAnnotationProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    for(Element annotatedElement : env.getElementsAnnotatedWith(ZerocellReaderBuilder.class)) {
        if (annotatedElement.getKind() != ElementKind.CLASS) {
            env.errorRaised();
            return true;
        }
        TypeElement classElement = (TypeElement) annotatedElement;
        try {
            ZerocellReaderBuilder annotation = annotatedElement.getAnnotation(ZerocellReaderBuilder.class);
            Optional<String> customReaderName =  Optional.empty();
            String name = annotation.value();
            if (!name.equals("__none__") && !name.isEmpty()) {
                customReaderName = Optional.of(name);
            }
            ReaderTypeSpec spec = new ReaderTypeSpec(classElement, customReaderName);
            JavaFile javaFile = spec.build();
            javaFile.writeTo(filer);
        } catch (Exception ioe) {
            ioe.printStackTrace();
            messager.printMessage(Diagnostic.Kind.ERROR,
                    String.format("Failed to generate the Reader class for %s, got exception: %s",
                        classElement.getQualifiedName().toString(),
                        ioe.getMessage()),
                    annotatedElement);
            env.errorRaised();
            return true;
        }
    }
    return false;
}
 
Example 19
Source Project: spring-openapi   Source File: ClientGeneratorUtils.java    License: MIT License 5 votes vote down vote up
public static void buildTypeSpec(String targetPackage, TypeSpec.Builder typeSpecBuilder, String outputPath) {
	try {
		JavaFile.builder(targetPackage, typeSpecBuilder.build())
				.build()
				.writeTo(new File(outputPath));
	} catch (IOException e) {
		e.printStackTrace(); // TODO
	}
}
 
Example 20
Source Project: aircon   Source File: SimpleProcessor.java    License: MIT License 5 votes vote down vote up
protected void writeClassToFile(final Element element, String packageName, TypeSpec typeSpec) {
	try {
		JavaFile.builder(packageName, typeSpec)
		        .build()
		        .writeTo(mProcessingEnvironment.getFiler());
	} catch (IOException e) {
		if (element != null) {
			mProcessingUtils.getLogger()
			                .e(element, "Unable to write remote config api for class: %s", element.getSimpleName());
		}
	}
}
 
Example 21
@Override
public void generate() {
    TypeSpec.Builder builder = TypeSpec.classBuilder(FINDER_CLASS_NAME)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    MethodSpec.Builder getMethodBuilder = MethodSpec.methodBuilder("get")
            .addModifiers(Modifier.STATIC, Modifier.PUBLIC)
            .addAnnotation(ClassName.get("android.support.annotation", "Nullable"))
            .returns(Object.class)
            .addParameter(Object.class, "obj");

    for (Element element : mElements) {
        if (element instanceof TypeElement) {
            TypeElement typeElement = (TypeElement) element;
            final String name = typeElement.getQualifiedName().toString() + PROXY_SUFFIX;
            final String packageName = name.substring(0, name.lastIndexOf("."));
            final String className = name.substring(packageName.length() + 1);
            final ClassName classType = ClassName.get(packageName, className);
            getMethodBuilder.beginControlFlow("if ($T.is(obj))", classType)
                    .addCode("return new $T(($L)obj);", classType, typeElement.getQualifiedName().toString())
                    .endControlFlow();
        }
    }
    getMethodBuilder.addStatement("return null");
    builder.addMethod(getMethodBuilder.build());
    JavaFile javaFile = JavaFile.builder(PACKAGE_NAME, builder.build()).build();
    try {
        javaFile.writeTo(mFiler);
    } catch (Exception e) {
    }
}
 
Example 22
Source Project: componentrouter   Source File: ElementGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void generate() {
    String qualifiedName = mElement.getQualifiedName().toString();
    String packageName = qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
    String className = qualifiedName.substring(packageName.length() + 1);
    try {
        JavaFile javaFile = JavaFile.builder(packageName, onCreateTypeSpec(mElement, packageName, className)).build();
        javaFile.writeTo(mFiler);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 23
Source Project: tysq-android   Source File: JavaPencil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void write(String path,
                         String pkgName,
                         TypeSpec typeSpec) throws IOException {
    // 生成java类
    JavaFile javaFile = JavaFile
            .builder(pkgName, typeSpec)
            .build();

    // 输出文件,注意这里不用再带类名
    javaFile.writeTo(new File(path));
}
 
Example 24
Source Project: web3j   Source File: Generator.java    License: Apache License 2.0 5 votes vote down vote up
void write(String packageName, TypeSpec typeSpec, String destinationDir) throws IOException {
    JavaFile javaFile =
            JavaFile.builder(packageName, typeSpec)
                    .indent("    ")
                    .skipJavaLangImports(true)
                    .build();

    javaFile.writeTo(new File(destinationDir));
}
 
Example 25
@Test
public void testGenerateHasDataFormat() {
    final TypeSpec spec = new GenerateYamlParserSupportClasses().generateHasDataFormat();
    final JavaFile file = JavaFile.builder("org.apache.camel.k.loader.yaml.parser", spec).build();

    assertThat(file.packageName).isEqualTo("org.apache.camel.k.loader.yaml.parser");
    assertThat(spec.name).isEqualTo("HasDataFormat");
    assertThat(spec.methodSpecs).isNotEmpty();
}
 
Example 26
@Test
public void testGenerateHasExpression() {
    final TypeSpec spec = new GenerateYamlParserSupportClasses().generateHasExpression();
    final JavaFile file = JavaFile.builder("org.apache.camel.k.loader.yaml.parser", spec).build();

    assertThat(file.packageName).isEqualTo("org.apache.camel.k.loader.yaml.parser");
    assertThat(spec.name).isEqualTo("HasExpression");
    assertThat(spec.methodSpecs).isNotEmpty();
}
 
Example 27
Source Project: Moxy   Source File: ViewStateProviderClassGenerator.java    License: MIT License 5 votes vote down vote up
@Override
public List<JavaFile> generate(PresenterInfo presenterInfo) {
	TypeSpec typeSpec = TypeSpec.classBuilder(presenterInfo.getName().simpleName() + MvpProcessor.VIEW_STATE_PROVIDER_SUFFIX)
			.addModifiers(Modifier.PUBLIC)
			.superclass(ViewStateProvider.class)
			.addMethod(generateGetViewStateMethod(presenterInfo.getName(), presenterInfo.getViewStateName()))
			.build();

	JavaFile javaFile = JavaFile.builder(presenterInfo.getName().packageName(), typeSpec)
			.indent("\t")
			.build();

	return Collections.singletonList(javaFile);
}
 
Example 28
Source Project: motif   Source File: CasesGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates the matching cases class and returns it as a {@link JavaFile}.
 */
public JavaFile generate() {
  MethodSpec privateConstructor = MethodSpec.constructorBuilder()
      .addModifiers(Modifier.PRIVATE)
      .build();

  TypeSpec.Builder casesClassBuilder = TypeSpec.classBuilder(className)
      .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
      .addMethod(privateConstructor)
      .addMethods(methods);

  for (String javadoc : javadocs) {
    casesClassBuilder.addJavadoc(javadoc);
  }

  TypeSpec casesClass = casesClassBuilder.build();

  JavaFile.Builder javaFileBuilder = JavaFile.builder(packageName, casesClass);

  if (fileComment != null) {
    javaFileBuilder.addFileComment(fileComment);
  }

  javaFileBuilder.addFileComment("\nGenerated by Motif. Do Not Edit!\n");

  JavaFile javaFile = javaFileBuilder.build();
  return javaFile;
}
 
Example 29
Source Project: EasyRouter   Source File: RouterAnnotationGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据之前收集到的数据信息(String url, Class target)
 * 生成路由表的.java文件代码
 * @param elementUtils
 * @param filer
 * @throws IOException
 */
public void generateCode(Elements elementUtils, Filer filer) throws IOException{
    if (datas.size() > 0){
        FieldSpec routerTable = getTableField();
        MethodSpec queryTable = getQueryMethod();
        MethodSpec initTable = getInjectMethod();
        MethodSpec constructor = getConstructorMethod(routerTable, initTable);
        TypeSpec routerTableClass = getClassType(routerTable, queryTable, initTable, constructor);

        String packageName = Constant.GENERATED_PACKAGENAME;
        JavaFile javaFile = JavaFile.builder(packageName, routerTableClass).build();
        javaFile.writeTo(filer);
    }
}
 
Example 30
Source Project: JIMU   Source File: RouterProcessor.java    License: Apache License 2.0 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

    TypeElement typeBaseCompRouter = elements.getTypeElement(BASECOMPROUTER);

    if (typeBaseCompRouter == null) {
        logger.error(Constants.MISSING_BASECOMPROUTER_MSG);
        return;
    }

    ClassName superClass = ClassName.get(typeBaseCompRouter);

    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();
    }
}