Java 类com.squareup.javapoet.JavaFile 实例源码

项目:slimorm    文件:SlimOrmProcessor.java   
private void generateClass(TypeElement typeElement, List<VariableElement> listOfVariables) {

        final ClassName pojoType = ClassName.get(typeElement);

        TypeSpec.Builder classBuilder = TypeSpec.
                classBuilder(typeElement.getSimpleName() + "Converter")
                .addModifiers(Modifier.PUBLIC);

        classBuilder.addMethod(generateSingleRowParseMethod(typeElement, listOfVariables, "toSingleRow", Modifier.PUBLIC));
        classBuilder.addMethod(generateSingleRowParseMethod(typeElement, listOfVariables, "parseToSingleRow", Modifier.PUBLIC, Modifier.STATIC));

        classBuilder.addMethod(generateListParseMethod(pojoType, "toList", "toSingleRow", Modifier.PUBLIC));
        classBuilder.addMethod(generateListParseMethod(pojoType, "parseToList", "parseToSingleRow", Modifier.PUBLIC, Modifier.STATIC));

        classBuilder.addMethod(generateToContentValuesMethod(typeElement, listOfVariables, "toContentValues", Modifier.PUBLIC));
        classBuilder.addMethod(generateToContentValuesMethod(typeElement, listOfVariables, "parseToContentValues", Modifier.PUBLIC, Modifier.STATIC));

        try {
            JavaFile.builder(pojoType.packageName(), classBuilder.build())
                    .build()
                    .writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
项目:GitHub    文件:ButterKnifeProcessor.java   
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
  Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);

  for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
    TypeElement typeElement = entry.getKey();
    BindingSet binding = entry.getValue();

    JavaFile javaFile = binding.brewJava(sdk);
    try {
      javaFile.writeTo(filer);
    } catch (IOException e) {
      error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
    }
  }

  return false;
}
项目:Alligator    文件:NavigationFactoryGenerator.java   
public JavaFile generate(List<RegistrationAnnotatedClass> annotatedClasses) throws ProcessingException {
    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC);

    for (RegistrationAnnotatedClass annotatedClass : annotatedClasses) {
        ClassName annotatedClassName = ClassName.get(annotatedClass.getClassElement());
        ClassName screenClassName = ClassName.bestGuess(annotatedClass.getScreenClassName());

        if (annotatedClass.getScreenResultClassName() == null) {
            String registrationMethod = getRegistrationMethod(annotatedClass.getScreenType());
            constructorBuilder.addStatement(registrationMethod, screenClassName, annotatedClassName);
        } else {
            String registrationForResultMethod = getRegistrationForResultMethod(annotatedClass.getScreenType());
            ClassName screenResultClassName = ClassName.bestGuess(annotatedClass.getScreenResultClassName());
            constructorBuilder.addStatement(registrationForResultMethod, screenClassName, annotatedClassName, screenResultClassName);
        }
    }

    TypeSpec navigationFactory = TypeSpec.classBuilder(CLASS_NAME)
            .addModifiers(Modifier.PUBLIC)
            .superclass(ClassName.get(PACKAGE, SUPERCLASS_NAME))
            .addMethod(constructorBuilder.build())
            .build();

    return JavaFile.builder(PACKAGE, navigationFactory).build();
}
项目:DaggerAutoInject    文件:DaggerAutoInjectProcessor.java   
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();
    }
}
项目:butterknife-parent    文件:ButterKnifeProcessor.java   
@Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
  Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);

  for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
    TypeElement typeElement = entry.getKey();
    BindingSet binding = entry.getValue();

    JavaFile javaFile = binding.brewJava(sdk);
    try {
      javaFile.writeTo(filer);
    } catch (IOException e) {
      error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
    }
  }

  return false;
}
项目:RxRetroJsoup    文件:RetroJsoupProcessor.java   
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();
        }
    }
项目:json-log-domain    文件:JavaGenerator.java   
public static void generate(Domain ontology, Path outputDirectory) throws IOException {
    JavaFile tags = TagGenerator.tag(ontology);
    JavaFile marker = MarkerGenerator.marker(ontology);
    JavaFile builder = MarkerGenerator.markerBuilder(ontology);
    JavaFile statement = LoggerGenerator.statement(ontology);
    JavaFile logger = LoggerGenerator.logger(ontology);
    JavaFile mdc = MdcGenerator.statement(ontology);

    Files.createDirectories(outputDirectory);

    for(JavaFile file : new JavaFile[]{tags, marker, builder, statement, logger, mdc}) {
        if(file != null) {
            if(changed(file, outputDirectory)) {
                file.writeTo(outputDirectory);
            } else {
                // do not write this file
            }
        }
    }
}
项目:json-log-domain    文件:LoggerGenerator.java   
public static JavaFile logger(Domain ontology) {
    ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + LOGGER);

    ClassName statementName = ClassName.get(ontology.getTargetPackage(), ontology.getName() + STATEMENT);

    ParameterSpec loggerParameter = ParameterSpec.builder(org.slf4j.Logger.class, "logger").build();

    return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name)
        .superclass(ParameterizedTypeName.get(ClassName.get(AbstractDomainLogger.class), statementName))                
        .addJavadoc(composeJavadoc(ontology, name))
        .addModifiers(Modifier.PUBLIC)
        .addMethod(MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addParameter(loggerParameter)
            .addStatement("super($N)", loggerParameter)
            .build())
        .addMethod(getCreateLogStatementMethod(statementName)).build()).build();
}
项目:prefpin    文件:PrefPinProcessor.java   
private void writeBinding(String targetClassName, Set<Element> annotationFields)
    throws IOException {
  String packageName = null;
  int lastDot = targetClassName.lastIndexOf('.');
  if (lastDot > 0) {
    packageName = targetClassName.substring(0, lastDot);
  }

  String targetSimpleClassName = targetClassName.substring(lastDot + 1);
  String bindingClassName = targetClassName + "_PrefBinding";
  String bindingSimpleClassName = bindingClassName.substring(lastDot + 1);

  ClassName targetClass = ClassName.get(packageName, targetSimpleClassName);

  TypeSpec binding = TypeSpec.classBuilder(bindingSimpleClassName)
      .addModifiers(Modifier.PUBLIC)
      .addMethod(buildConstructor(targetClass, annotationFields))
      .build();

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

  javaFile.writeTo(processingEnv.getFiler());
}
项目:ActivityBuilder    文件:ConsumerHelper.java   
private static ClassName writeConsumer(int count) throws IOException {
  String packageName = "info.dourok.esactivity.function";
  MethodSpec.Builder method = MethodSpec.methodBuilder("accept")
      .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);

  TypeSpec.Builder type = TypeSpec.interfaceBuilder("Consumer" + count)
      .addModifiers(Modifier.PUBLIC);
  for (int i = 0; i < count; i++) {
    type.addTypeVariable(TypeVariableName.get("T" + i));
    method.addParameter(
        TypeVariableName.get("T" + i), "t" + i);
  }
  type.addMethod(method.build());
  JavaFile.builder(packageName, type.build())
      .build()
      .writeTo(EasyUtils.getFiler());
  return ClassName.get(packageName, "Consumer" + count);
}
项目:AnnotationProcessorStarter    文件:AnnotatedClass.java   
public void writeInto(final Filer pFiler, final Messager pMessager) {
    // prepare generated class
    final GeneratedClass lGeneratedClass = new GeneratedClass(mEnclosingClass, mMethods);

    final TypeSpec lTypeSpecGeneratedClass = lGeneratedClass.buildTypeSpec();
    final String lPackageName = lGeneratedClass.packageName();

    // create generated class to a file
    try {
        JavaFile.builder(lPackageName, lTypeSpecGeneratedClass)
                .build()
                .writeTo(pFiler);
    } catch (IOException pE) {
        logError(pMessager, mEnclosingClass, "error while writing generated class");
    }
}
项目:r-parser    文件:ExampleProcessor.java   
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    parser.scan(roundEnvironment);
    TypeSpec.Builder builder = TypeSpec.classBuilder("Testing")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    for (Element element : roundEnvironment.getElementsAnnotatedWith(Parse.class))
        builder.addField(FieldSpec.builder(String.class, element.getSimpleName().toString())
                .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                .initializer("$S", parser.parse("com.example.rparser", element.getAnnotation(Parse.class).value()))
                .build());
    JavaFile javaFile = JavaFile.builder("com.example.rparser", builder.build())
            .build();
    try {
        javaFile.writeTo(filer);
    } catch (IOException ignored) {
    }
    return false;
}
项目:Stitch    文件:StitchProcessor.java   
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment env) {
    Map<TypeElement, StitchGenerator> stitchGeneratorMap = processAnnotations(env);
    for (Entry<TypeElement, StitchGenerator> typeElementCodeGeneratorEntry : stitchGeneratorMap
            .entrySet()) {
        TypeElement typeElement = typeElementCodeGeneratorEntry.getKey();
        StitchGenerator stitchGenerator = typeElementCodeGeneratorEntry.getValue();
        JavaFile javaFile = stitchGenerator.makeFile();
        try {
            javaFile.writeTo(processingEnv.getFiler());
        } catch (IOException e) {
            mMessager.printMessage(Kind.ERROR, String
                    .format("Unable to write binding for type %s: %s",
                            typeElement.getSimpleName(),
                            e.getMessage()));
        }
    }
    return false;
}
项目:DeeplinkRouter    文件:DeeplinkRouterProcessor.java   
private void innerGenerateRouterInit(MethodSpec.Builder methodBuilder)
{
    TypeSpec routerInit = TypeSpec.classBuilder(ROUTER_INIT_CLASS_NAME)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addSuperinterface(ClassName.get(ROUTER_API_PACKAGE_NAME, ROUTER_INIT_INTERFACE_NAME))
            .addMethod(methodBuilder.build())
            .build();
    try
    {
        JavaFile.builder(ROUTER_API_PACKAGE_NAME, routerInit)
                .build()
                .writeTo(mFiler);
    }
    catch (Exception e)
    {
        error("Failed to generate file %s", routerInit.name);
    }
}
项目:auto    文件:DecoratorProcessor.java   
private JavaFile process(EnrichedTypeElement element) throws AbortProcessingException {
  TypeSpec.Builder builder = TypeSpec.classBuilder(element.getClassName(DECORATOR_SUFFIX))
      .addModifiers(element.getAccessModifier())
      .addTypeVariables(element.getTypeVariables())
      .addField(createDelegateFieldSpec(element))
      .addMethod(createConstructorMethod(element))
      .addMethods(createOverridingMethods(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");
  }

  return JavaFile.builder(element.getPackageName(), builder.build())
      .build();
}
项目:D-Router    文件:RouterTableGenerator.java   
public void generateMappingTable(Filer filer) throws IOException {
    if (routerTable.isEmpty()) {
        return;
    }
    FieldSpec tableFieldSpec = FieldSpec.builder(Map.class, "routerTable")
            .addModifiers(Modifier.PRIVATE)
            .build();
    MethodSpec initTableMethodSpec = getInitTableMethodSpec();
    MethodSpec queryTableMethodSpec = getqueryTableMethodSpec();
    MethodSpec constructorMethodSpec = getconstructorMethodSpec(tableFieldSpec, initTableMethodSpec);
    MethodSpec addRouterMethodSpec = getAddRouterMethodSpec();
    TypeSpec routerTableClassTypeSpec = getRouterTableClassTypeSpec(tableFieldSpec, initTableMethodSpec, queryTableMethodSpec, constructorMethodSpec, addRouterMethodSpec);
    String packageName = Constants.GENERATED_PACKAGE_NAME;
    JavaFile javaFile = JavaFile.builder(packageName, routerTableClassTypeSpec).build();
    javaFile.writeTo(filer);
}
项目:Spyglass    文件:TestGetDefaultMethodGenerator.java   
private void checkCompiles(final MethodSpec method) {
    final TypeSpec wrapperTypeSpec = CallerDef
            .getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
            .addMethod(CallerDef.getNewCallMethodPrototype().build())
            .addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
            .addMethod(method)
            .build();

    final JavaFile wrapperJavaFile = JavaFile
            .builder("", wrapperTypeSpec)
            .build();

    final Set<JavaFile> filesToCompile = new HashSet<>();
    filesToCompile.add(wrapperJavaFile);
    filesToCompile.add(CallerDef.SRC_FILE);

    CompileChecker.checkCompiles(filesToCompile);
}
项目:Spyglass    文件:TestGetPlaceholderMethodGenerator.java   
private void checkCompiles(final MethodSpec method) {
    final TypeSpec wrapperTypeSpec = CallerDef
            .getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
            .addMethod(CallerDef.getNewCallMethodPrototype().build())
            .addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
            .addMethod(method)
            .build();

    final JavaFile wrapperJavaFile = JavaFile
            .builder("", wrapperTypeSpec)
            .build();

    final Set<JavaFile> filesToCompile = new HashSet<>();
    filesToCompile.add(wrapperJavaFile);
    filesToCompile.add(CallerDef.SRC_FILE);

    CompileChecker.checkCompiles(filesToCompile);
}
项目:Spyglass    文件:TestValueIsAvailableMethodGenerator.java   
private void checkCompiles(final MethodSpec method) {
    final TypeSpec wrapperTypeSpec = CallerDef
            .getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
            .addMethod(CallerDef.getNewCallMethodPrototype().build())
            .addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
            .addMethod(method)
            .build();

    final JavaFile wrapperJavaFile = JavaFile
            .builder("", wrapperTypeSpec)
            .build();

    final Set<JavaFile> filesToCompile = new HashSet<>();
    filesToCompile.add(wrapperJavaFile);
    filesToCompile.add(CallerDef.SRC_FILE);

    CompileChecker.checkCompiles(filesToCompile);
}
项目:Spyglass    文件:TestGetValueMethodGenerator.java   
private void checkCompiles(final MethodSpec method) {
    final TypeSpec wrapperTypeSpec = CallerDef
            .getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
            .addMethod(CallerDef.getNewCallMethodPrototype().build())
            .addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
            .addMethod(method)
            .build();

    final JavaFile wrapperJavaFile = JavaFile
            .builder("", wrapperTypeSpec)
            .build();

    final Set<JavaFile> filesToCompile = new HashSet<>();
    filesToCompile.add(wrapperJavaFile);
    filesToCompile.add(CallerDef.SRC_FILE);

    CompileChecker.checkCompiles(filesToCompile);
}
项目:immu    文件:ImmuCompilerTest.java   
@Test
public void write_withIOException() throws Exception {
  final ProcessingEnvironment env = mock(ProcessingEnvironment.class);
  final Messager messager = mock(Messager.class);
  final Filer filer = mock(Filer.class);

  when(env.getMessager()).thenReturn(messager);
  when(env.getFiler()).thenReturn(filer);

  compiler.init(env);

  final JavaFile javaFile = mock(JavaFile.class);
  doThrow(IOException.class).when(javaFile).writeTo(any(Filer.class));

  compiler.writeSource(javaFile);

  verify(messager, times(1)).printMessage(eq(Diagnostic.Kind.ERROR), any());
}
项目:data-mediator    文件:SharedPropertiesNGenerator.java   
public static boolean generateSharedProperties(Collection<FieldData> fields,
                                               Elements elements, Filer filer, ProcessorPrinter pp){
    final ClassName cn_sp = ClassName.get(PKG_DM_INTERNAL, SIMPLE_NAME_SHARED_PROP);
    CodeBlock.Builder staticBuilder = CodeBlock.builder();
    for(FieldData fd : fields){
        staticBuilder.add("$T.putToCache($S, $S, $L);\n", cn_sp, fd.getTypeCompat().toString(),
                fd.getPropertyName(), fd.getComplexType());
    }
    String classSimpleName = SIMPLE_NAME_SHARED_PROP + "_" + findBestIndex(elements);
    TypeSpec typeSpec = TypeSpec.classBuilder(classSimpleName)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addStaticBlock(staticBuilder.build())
            .addJavadoc(CodeBlock.of(DOC))
            .build();

    try {
        JavaFile javaFile = JavaFile.builder(PKG_DM_INTERNAL, typeSpec)
                .build();
       // System.out.println(javaFile.toString());
        javaFile.writeTo(filer);
    } catch (IOException e) {
        pp.error(TAG, "generateSharedProperties", Util.toString(e));
        return false;
    }
    return true;
}
项目:auto    文件:NoOpProcessor.java   
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();
}
项目:jdoocsoup    文件:JDoocsSoupAnnotationProcessor.java   
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());
    }
}
项目:GitHub    文件:ProcessorUtil.java   
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);
  }
}
项目:auto-nav    文件:NavProcessor.java   
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();
        }

    }
项目:GitHub    文件:DelegateClassGenerator.java   
@Override
public JavaFile build() {
    TypeSpec.Builder result =
            TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC)
                    .addSuperinterface(
                            ParameterizedTypeName.get(VIEW_DELEGATE, viewClass,
                                                      getPresenterFactoryTypeName()));
    decorator.build(result);
    return JavaFile.builder(getPackageName(), result.build())
            .addFileComment("Generated class from EasyMVP. Do not modify!").build();
}
项目:Rx.Observe    文件:RxObserveProcessor.java   
private void writeRxObserve() {
    final TypeSpec.Builder builder = TypeSpec.classBuilder(Constants.CLASS)
            .addModifiers(Modifier.PUBLIC);

    for (ClassName className : observeHolders.keySet()) {
        final ObserveHolder observeHolder = observeHolders.get(className);
        final String simpleName = className.simpleName();
        final TypeName returnType = ClassName.bestGuess(className.packageName() + "." + simpleName + Constants.OBSERVE_CLASS);

        if (processUtils.allMethodsAreStatic(observeHolder.methods)) {
            builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_OF + simpleName)
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .returns(returnType)
                    .addStatement("return new $T()", returnType)
                    .build());
        } else {
            builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_OF)
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .addParameter(className, Constants.TARGET)
                    .returns(returnType)
                    .addStatement("return new $T($L)", returnType, Constants.TARGET)
                    .build());
        }
    }

    final TypeSpec newClass = builder.build();

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

    try {
        javaFile.writeTo(System.out);
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:GitHub    文件:ProcessorUtil.java   
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);
  }
}
项目:GitHub    文件:ObjectMapperInjector.java   
public String getJavaClassFile() {
    try {
        return JavaFile.builder(mJsonObjectHolder.packageName, getTypeSpec()).build().toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
项目:easybundler    文件:Bundler.java   
/**
 * Process the BundlerClass and return the source of a generated Bundler class, as a String.
 * The output of this method is intended for writing to a ".java" file.
 */
public String getBundlerClassSource() {
    // Create class named {FooObject}Bundler
    TypeSpec bundlerType = TypeSpec.classBuilder(getBundlerClassName())
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(createToBundleMethod())
            .addMethod(createFromBundleMethod())
            .build();

    JavaFile javaFile = JavaFile.builder(info.className.packageName(), bundlerType)
            .build();

    return javaFile.toString();
}
项目:greycat    文件:Generator.java   
private void generateJava(String packageName, String pluginName, File target) {
    List<JavaFile> collector = new ArrayList<JavaFile>();
    TypeGenerator.generate(packageName, model, collector);
    IndexGenerator.generate(packageName, model, collector);
    ConstantGenerator.generate(packageName, model, collector);
    PluginGenerator.generate(packageName, pluginName, model, collector);
    for (JavaFile file : collector) {
        try {
            file.writeTo(target);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
项目:android-state    文件:StateProcessor.java   
private boolean writeJavaFile(JavaFile javaFile) {
    StringBuilder builder = new StringBuilder();

    JavaFileObject filerSourceFile = null;

    try {
        builder.append(LICENSE_HEADER);
        javaFile.writeTo(builder);

        String fileName = javaFile.packageName.isEmpty() ? javaFile.typeSpec.name : javaFile.packageName + "." + javaFile.typeSpec.name;
        List<Element> originatingElements = javaFile.typeSpec.originatingElements;
        filerSourceFile = mFiler.createSourceFile(fileName, originatingElements.toArray(new Element[originatingElements.size()]));

        try (Writer writer = filerSourceFile.openWriter()) {
            writer.write(builder.toString());
        }
        return true;

    } catch (Exception e) {
        mMessager.printMessage(Diagnostic.Kind.ERROR, "Couldn't generate classes " + javaFile.packageName + '.' + javaFile.typeSpec.name);
        e.printStackTrace();

        if (filerSourceFile != null) {
            filerSourceFile.delete();
        }

        return false;
    }
}
项目:konohana    文件:StoreWriter.java   
private void write() {
    try {
        JavaFile.builder(storeDefinition.getInterfaceName().packageName(), buildTypeSpec())
                .build()
                .writeTo(storeDefinition.getFiler());
    } catch (IOException e) {
        throw storeDefinition.newProcessingException(e);
    }
}
项目:lazythreetenbp    文件:JavaWriter.java   
void writeZoneIds(String version, Set<String> zoneIds) throws IOException {
    TypeSpec typeSpec = TypeSpec.classBuilder("LazyZoneRules")
            .addModifiers(FINAL)
            .addField(version(version))
            .addField(regionId(zoneIds))
            .build();

    if (!Files.exists(outputDir)) {
        Files.createDirectories(outputDir);
    }
    JavaFile.builder("com.gabrielittner.threetenbp", typeSpec)
            .build()
            .writeTo(outputDir);
}
项目:limitjson    文件:LJSONAnnotatedClass.java   
public static void toWrite(ProcessorHelper helper, LJSONTypeElement ljsonElement, Filer filer) throws IOException {

        // create common ClassName
        ClassName thisObj = ClassName.bestGuess(ljsonElement.getTypeName());
        ClassName jsonObject = ClassName.get("org.json", "JSONObject");

        MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create")
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                .returns(thisObj)
                .addParameter(ClassName.get(String.class), "json", Modifier.FINAL)
                .addParameter(TypeName.BOOLEAN, "allowNull", Modifier.FINAL)
                .addStatement("$T thisObj = new $T()", thisObj, thisObj)
                .beginControlFlow("try")
                .addStatement("$T root = new $T(json)", jsonObject, jsonObject);

        List<LIMITJSONVariable> ljsonVariableElements = ljsonElement.getVariableElements();
        addLJSONVariable(helper, createMethod, ljsonVariableElements);

        createMethod.nextControlFlow("catch (Exception e)")
                .beginControlFlow("if (allowNull)")
                .addStatement("return null")
                .endControlFlow()
                .endControlFlow();

        createMethod.addStatement("return thisObj");
        // generate whole class
        TypeSpec finderClass = TypeSpec.classBuilder(ljsonElement.getTypeName() + "$$CREATOR")
                .addModifiers(Modifier.PUBLIC)
//                .addSuperinterface(ParameterizedTypeName.get(ClassName.get(CORE_PACKAGE_NAME, "Core"), TypeName.get(classElement.asType())))
                .addMethod(createMethod.build())
//                .addMethod(parseIntentBuilder.build())
//                .addMethod(saveInstanceStateBuilder.build())
                .build();

        String packageName = ljsonElement.getTypePackageName();
        // generate file
        JavaFile.builder(packageName, finderClass).build().writeTo(filer);
    }
项目:Hannibai    文件:ElementGenerator.java   
@Override
public void generate() {
    try {
        JavaFile.builder(mPackageName, onCreateTypeSpec(mElement, mPackageName, mClassName))
                .build()
                .writeTo(EnvironmentManager.getManager().getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:Surgeon    文件:SurgeonProcessor.java   
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment env) {
    List<JavaFile> files = findAndParseTargets(env);
    for (JavaFile javaFile : files) {
        try {
            javaFile.writeTo(filer);
        } catch (IOException e) {
            error("Unable to write same name %s: %s", javaFile.packageName, e.getMessage());
        }
    }
    return false;
}
项目:DDComponentForAndroid    文件:RouterProcessor.java   
/**
 * 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();
    }
}
项目:json-log-domain    文件:MdcGenerator.java   
public static JavaFile statement(Domain ontology) {

    ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + MARKER_MDC);

    ClassName markerName = MarkerGenerator.getName(ontology);

    TypeName wildcard = WildcardTypeName.subtypeOf(DomainMarker.class);
    TypeName classOfAny = ParameterizedTypeName.get(ClassName.get(Class.class), wildcard);

    ParameterSpec type = ParameterSpec.builder(classOfAny, "type").build();

    return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name)
                .superclass(ParameterizedTypeName.get( ClassName.get(DomainMdc.class), markerName))
                .addModifiers(Modifier.PUBLIC)
                .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PUBLIC)
                    .addStatement("super($T.QUALIFIER)", markerName)
                    .build()
                )
                .addMethod(MethodSpec.methodBuilder("createMarker")
                        .addModifiers(Modifier.PUBLIC)
                        .addStatement("return new $T()", markerName)
                        .returns(markerName)
                        .build()
                    )
                .addMethod(MethodSpec.methodBuilder("supports")
                        .addModifiers(Modifier.PUBLIC)
                        .addParameter(type)
                        .addStatement("return $T.class == $N", markerName, type)
                        .returns(boolean.class)
                        .build()
                    )
                .build())

            .build();
}