Java Code Examples for com.squareup.javapoet.JavaFile#writeTo()
The following examples show how to use
com.squareup.javapoet.JavaFile#writeTo() .
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: RetrofitServiceProcessor.java From kaif-android with Apache License 2.0 | 6 votes |
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 2
Source File: OptionalCasesGenerator.java From motif with Apache License 2.0 | 6 votes |
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 3
Source File: RetroJsoupProcessor.java From RxRetroJsoup with Apache License 2.0 | 6 votes |
public void construct(JsoupModelHolder modelHolder) { final TypeSpec.Builder builder = TypeSpec.classBuilder(modelHolder.className + Constants.PARSER) .addModifiers(Modifier.PUBLIC); for (JsoupModelFieldHolder field : modelHolder.fields) { builder.addMethod(MethodSpec.methodBuilder(field.name.replace("-","_").replace(" ","_")) .addModifiers(Modifier.PUBLIC) .returns(TypeName.VOID) .addParameter(modelHolder.classNameComplete, "item") .addParameter(TypeName.get(String.class), "value") .addStatement("item.$L = value", field.name) .build()); } final TypeSpec newClass = builder.build(); final JavaFile javaFile = JavaFile.builder(modelHolder.classNameComplete.packageName(), newClass).build(); try { javaFile.writeTo(System.out); javaFile.writeTo(filer); } catch (IOException e) { e.printStackTrace(); } }
Example 4
Source File: JavaClassGenerator.java From web3j with Apache License 2.0 | 6 votes |
@Override public void writeClass() throws IOException { ClassName EVM_ANNOTATION = ClassName.get("org.web3j", "EVMTest"); AnnotationSpec.Builder annotationSpec = AnnotationSpec.builder(EVM_ANNOTATION); if (JavaVersion.getJavaVersionAsDouble() < 11) { ClassName GethContainer = ClassName.get("org.web3j", "NodeType"); annotationSpec.addMember("value", "type = $T.GETH", GethContainer); } TypeSpec testClass = TypeSpec.classBuilder(theContract.getSimpleName() + "Test") .addMethods(MethodFilter.generateMethodSpecsForEachTest(theContract)) .addAnnotation((annotationSpec).build()) .addField( theContract, toCamelCase(theContract), Modifier.PRIVATE, Modifier.STATIC) .build(); JavaFile javaFile = JavaFile.builder(packageName, testClass).build(); javaFile.writeTo(new File(writePath)); }
Example 5
Source File: DaggerAutoInjectProcessor.java From DaggerAutoInject with Apache License 2.0 | 6 votes |
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 6
Source File: OnActivityResultProcessor.java From OnActivityResult with Apache License 2.0 | 5 votes |
private void writeActivityResultClasses(final Map<String, ActivityResultClass> activityResultClasses) { for (final ActivityResultClass activityResultClass : activityResultClasses.values()) { final JavaFile javaFile = activityResultClass.brewJava(); try { javaFile.writeTo(filer); } catch (final IOException e) { processingEnv.getMessager().printMessage(ERROR, String.format("Could not write to file %s", activityResultClass.toString())); } } }
Example 7
Source File: FilerGenerator.java From Smirk with MIT License | 5 votes |
@Override public void generate() { String qualifiedName = mElement.getQualifiedName().toString(); String packageName = qualifiedName.substring(0, qualifiedName.lastIndexOf(".")); JavaFile javaFile = JavaFile.builder(packageName, onCreateTypeSpec(mElement)).build(); try { javaFile.writeTo(mFiler); } catch (Exception e) { e.printStackTrace(); } }
Example 8
Source File: Proto2Java.java From raptor with Apache License 2.0 | 5 votes |
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(generatedSourceDirectory)); } catch (IOException e) { throw new IOException("Failed to write " + javaFile.packageName + "." + javaFile.typeSpec.name + " to " + generatedSourceDirectory, e); } }
Example 9
Source File: SerializationProcessorUtil.java From bazel with Apache License 2.0 | 5 votes |
static JavaFile writeGeneratedClassToFile( Element element, TypeSpec builtClass, ProcessingEnvironment env) throws SerializationProcessingFailedException { String packageName = env.getElementUtils().getPackageOf(element).getQualifiedName().toString(); JavaFile file = JavaFile.builder(packageName, builtClass).build(); try { file.writeTo(env.getFiler()); } catch (IOException e) { throw new SerializationProcessingFailedException( element, "Failed to generate output file: %s", e.getMessage()); } return file; }
Example 10
Source File: EventProxyFiler.java From Aria with Apache License 2.0 | 5 votes |
private void createFile(JavaFile jf) throws IOException { if (ProxyConstance.DEBUG) { // 如果需要在控制台打印生成的文件,则去掉下面的注释 jf.writeTo(System.out); } else { jf.writeTo(mFiler); } }
Example 11
Source File: SlimConfigurationProcessor.java From spring-init with Apache License 2.0 | 5 votes |
private void write(TypeSpec type, String packageName) { JavaFile file = JavaFile.builder(packageName, type).build(); try { file.writeTo(this.filer); } catch (IOException ex) { throw new IllegalStateException(ex); } }
Example 12
Source File: CodeGeneration.java From requery with Apache License 2.0 | 5 votes |
static void writeType(ProcessingEnvironment processingEnvironment, String packageName, TypeSpec typeSpec) throws IOException { JavaFile file = JavaFile.builder(packageName, typeSpec) .addFileComment("Generated file do not edit, generated by " + EntityProcessor.class.getCanonicalName()) .indent(" ") .build(); file.writeTo(processingEnvironment.getFiler()); }
Example 13
Source File: Generator.java From etherscan-explorer with GNU General Public License v3.0 | 5 votes |
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 14
Source File: BindingClass.java From Aftermath with Apache License 2.0 | 5 votes |
void writeToFiler(Filer filer) throws IOException { ClassName targetClassName = ClassName.get(classPackage, targetClass); TypeSpec.Builder aftermath = TypeSpec.classBuilder(className) .addModifiers(Modifier.PUBLIC) .addTypeVariable(TypeVariableName.get("T", targetClassName)) .addMethod(generateOnActivityResultMethod()) .addMethod(generateOnRequestPermissionResultMethod()); ClassName callback = ClassName.get("org.michaelevans.aftermath", "IAftermathDelegate"); aftermath.addSuperinterface(ParameterizedTypeName.get(callback, TypeVariableName.get("T"))); JavaFile javaFile = JavaFile.builder(classPackage, aftermath.build()).build(); javaFile.writeTo(filer); }
Example 15
Source File: ZeroCellAnnotationProcessor.java From zerocell with Apache License 2.0 | 5 votes |
@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 16
Source File: TableProcessor.java From wellsql with MIT License | 4 votes |
private void generateLookup(MethodSpec constructor, FieldSpec tableMap, FieldSpec mapperMap) { TypeName anyClass = CodeGenUtils.wildcard(Class.class); TypeSpec.Builder lookupClassBuilder = TypeSpec.classBuilder(CodeGenUtils.LOOKUP_CLASS) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addSuperinterface(TableLookup.class); MethodSpec getTableTokens = CodeGenUtils.interfaceMethod("getTableTokens") .returns(ParameterizedTypeName.get(ClassName.get(Set.class), anyClass)) .addStatement("return $N.keySet()", tableMap) .build(); MethodSpec getMapperTokens = CodeGenUtils.interfaceMethod("getMapperTokens") .returns(ParameterizedTypeName.get(ClassName.get(Set.class), anyClass)) .addStatement("return $N.keySet()", mapperMap) .build(); MethodSpec getTable = CodeGenUtils.interfaceMethod("getTable") .returns(TableClass.class) .addParameter(anyClass, "token") .addStatement("return $N.get(token)", tableMap) .build(); TypeVariableName t = TypeVariableName.get("T"); ParameterizedTypeName parametrizedMapper = ParameterizedTypeName.get(ClassName.get(Mapper.class), t); ParameterizedTypeName parametrizedClass = ParameterizedTypeName.get(ClassName.get(Class.class), t); MethodSpec getMapper = CodeGenUtils.interfaceMethod("getMapper") .addTypeVariable(t) .returns(parametrizedMapper) .addParameter(ParameterSpec.builder(parametrizedClass, "token").build()) .addStatement("return ($T) $N.get(token)", parametrizedMapper, mapperMap) .build(); TypeSpec lookup = lookupClassBuilder.addField(tableMap).addField(mapperMap) .addMethod(constructor) .addMethod(getTableTokens) .addMethod(getMapperTokens) .addMethod(getTable) .addMethod(getMapper) .build(); JavaFile javaFile = JavaFile.builder(CodeGenUtils.PACKAGE, lookup).build(); try { javaFile.writeTo(filer); } catch (IOException e) { e.printStackTrace(); } }
Example 17
Source File: HiveWrapperGenerator.java From transport with BSD 2-Clause "Simplified" License | 4 votes |
private void generateWrapper(String topLevelClass, Collection<String> implementationClasses, File outputDir) { ClassName topLevelClassName = ClassName.bestGuess(topLevelClass); ClassName wrapperClassName = ClassName.get(topLevelClassName.packageName() + "." + HIVE_PACKAGE_SUFFIX, topLevelClassName.simpleName()); /* Generates -> @Override protected Class<? extends TopLevelStdUDF> getTopLevelUdfClass() { return ${topLevelClass}.class; } */ MethodSpec getTopLevelUdfClassMethod = MethodSpec.methodBuilder(GET_TOP_LEVEL_UDF_CLASS_METHOD) .addAnnotation(Override.class) .returns( ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(TopLevelStdUDF.class))) .addModifiers(Modifier.PROTECTED) .addStatement("return $T.class", topLevelClassName) .build(); /* Generates -> @Override protected List<? extends StdUDF> getStdUdfImplementations() { return ImmutableList.of( new ${implementationClasses(0)}(), new ${implementationClasses(1)}(), . . . ); } */ MethodSpec getStdUdfImplementationsMethod = MethodSpec.methodBuilder(GET_STD_UDF_IMPLEMENTATIONS_METHOD) .addAnnotation(Override.class) .returns(ParameterizedTypeName.get(ClassName.get(List.class), WildcardTypeName.subtypeOf(StdUDF.class))) .addModifiers(Modifier.PROTECTED) .addStatement("return $T.of($L)", ImmutableList.class, implementationClasses.stream() .map(clazz -> "new " + clazz + "()") .collect(Collectors.joining(", "))) .build(); /* Generates -> public class ${wrapperClassName} extends StdUdfWrapper { . . . } */ TypeSpec wrapperClass = TypeSpec.classBuilder(wrapperClassName) .addModifiers(Modifier.PUBLIC) .superclass(HIVE_STD_UDF_WRAPPER_CLASS_NAME) .addMethod(getTopLevelUdfClassMethod) .addMethod(getStdUdfImplementationsMethod) .build(); JavaFile javaFile = JavaFile.builder(wrapperClassName.packageName(), wrapperClass).build(); try { javaFile.writeTo(outputDir); } catch (Exception e) { throw new RuntimeException("Error writing wrapper to file", e); } }
Example 18
Source File: InterceptorProcessor.java From AndServer with Apache License 2.0 | 4 votes |
private void createRegister(String registerPackageName, Map<String, List<TypeElement>> interceptorMap) { TypeName listTypeName = ParameterizedTypeName.get(ClassName.get(List.class), mInterceptor); TypeName typeName = ParameterizedTypeName.get(ClassName.get(Map.class), mString, listTypeName); FieldSpec mapField = FieldSpec.builder(typeName, "mMap", Modifier.PRIVATE).build(); CodeBlock.Builder rootCode = CodeBlock.builder().addStatement("this.mMap = new $T<>()", HashMap.class); for (Map.Entry<String, List<TypeElement>> entry : interceptorMap.entrySet()) { String group = entry.getKey(); List<TypeElement> interceptorList = entry.getValue(); CodeBlock.Builder groupCode = CodeBlock.builder() .addStatement("List<$T> $LList = new $T<>()", mInterceptor, group, ArrayList.class); for (TypeElement type : interceptorList) { mLog.i(String.format("------ Processing %s ------", type.getSimpleName())); groupCode.addStatement("$LList.add(new $T())", group, type); } rootCode.add(groupCode.build()); rootCode.addStatement("this.mMap.put($S, $LList)", group, group); } MethodSpec rootMethod = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addCode(rootCode.build()) .build(); MethodSpec registerMethod = MethodSpec.methodBuilder("onRegister") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(mContext, "context") .addParameter(mString, "group") .addParameter(mRegisterType, "register") .addStatement("List<$T> list = mMap.get(group)", mInterceptor) .beginControlFlow("if(list != null && !list.isEmpty())") .beginControlFlow("for ($T interceptor : list)", mInterceptor) .addStatement("register.addInterceptor(interceptor)") .endControlFlow() .endControlFlow() .build(); TypeSpec adapterClass = TypeSpec.classBuilder("InterceptorRegister") .addJavadoc(Constants.DOC_EDIT_WARN) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addSuperinterface(mOnRegisterType) .addField(mapField) .addMethod(rootMethod) .addMethod(registerMethod) .build(); JavaFile javaFile = JavaFile.builder(registerPackageName, adapterClass).build(); try { javaFile.writeTo(mFiler); } catch (IOException e) { throw new RuntimeException(e); } }
Example 19
Source File: ReactModuleSpecProcessor.java From react-native-GPay with MIT License | 4 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Set<? extends Element> reactModuleListElements = roundEnv.getElementsAnnotatedWith( ReactModuleList.class); for (Element reactModuleListElement : reactModuleListElements) { if (!(reactModuleListElement instanceof TypeElement)) { continue; } TypeElement typeElement = (TypeElement) reactModuleListElement; ReactModuleList reactModuleList = typeElement.getAnnotation(ReactModuleList.class); if (reactModuleList == null) { continue; } ClassName className = ClassName.get(typeElement); String packageName = ClassName.get(typeElement).packageName(); String fileName = className.simpleName(); List<String> nativeModules = new ArrayList<>(); try { reactModuleList.nativeModules(); // throws MirroredTypesException } catch (MirroredTypesException mirroredTypesException) { List<? extends TypeMirror> typeMirrors = mirroredTypesException.getTypeMirrors(); for (TypeMirror typeMirror : typeMirrors) { nativeModules.add(typeMirror.toString()); } } MethodSpec getReactModuleInfosMethod; try { getReactModuleInfosMethod = MethodSpec.methodBuilder("getReactModuleInfos") .addAnnotation(Override.class) .addModifiers(PUBLIC) .addCode(getCodeBlockForReactModuleInfos(nativeModules)) .returns(MAP_TYPE) .build(); } catch (ReactModuleSpecException reactModuleSpecException) { mMessager.printMessage(ERROR, reactModuleSpecException.mMessage); return false; } TypeSpec reactModulesInfosTypeSpec = TypeSpec.classBuilder( fileName + "$$ReactModuleInfoProvider") .addModifiers(Modifier.PUBLIC) .addMethod(getReactModuleInfosMethod) .addSuperinterface(ReactModuleInfoProvider.class) .build(); JavaFile javaFile = JavaFile.builder(packageName, reactModulesInfosTypeSpec) .addFileComment("Generated by " + getClass().getName()) .build(); try { javaFile.writeTo(mFiler); } catch (IOException e) { e.printStackTrace(); } } return true; }
Example 20
Source File: ControllerProcessor.java From AndServer with Apache License 2.0 | 4 votes |
private void createHandlerAdapter(String registerPackageName, Map<TypeElement, List<ExecutableElement>> controllers) { Map<String, List<String>> adapterMap = new HashMap<>(); for (Map.Entry<TypeElement, List<ExecutableElement>> entry : controllers.entrySet()) { TypeElement type = entry.getKey(); List<ExecutableElement> executes = entry.getValue(); mLog.i(String.format("------ Processing %s ------", type.getSimpleName())); String typeName = type.getQualifiedName().toString(); Mapping typeMapping = getTypeMapping(type); validateMapping(typeMapping, typeName); TypeName controllerType = TypeName.get(type.asType()); FieldSpec hostField = FieldSpec.builder(controllerType, "mHost", Modifier.PRIVATE).build(); FieldSpec mappingField = FieldSpec.builder(mMappingList, "mMappingMap", Modifier.PRIVATE).build(); CodeBlock.Builder rootCode = CodeBlock.builder() .addStatement("this.mHost = new $T()", type) .addStatement("this.mMappingMap = new $T<>()", LinkedHashMap.class); for (ExecutableElement execute : executes) { Mapping mapping = getExecuteMapping(execute); validateExecuteMapping(mapping, typeName + "#" + execute.getSimpleName().toString() + "()"); mapping = new Merge(typeMapping, mapping); rootCode.beginControlFlow("\n").addStatement("$T mapping = new $T()", mMapping, mMapping); addMapping(rootCode, mapping); Addition addition = execute.getAnnotation(Addition.class); rootCode.add("\n").addStatement("$T addition = new $T()", mAddition, mAddition); addAddition(rootCode, addition); String handlerName = createHandler(type, execute, mapping.path(), mapping.isRest()); rootCode.addStatement("$L handler = new $L(mHost, mapping, addition, $L)", handlerName, handlerName, mapping.isRest()).addStatement("mMappingMap.put(mapping, handler)").endControlFlow(); } MethodSpec rootMethod = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addCode(rootCode.build()) .build(); MethodSpec mappingMethod = MethodSpec.methodBuilder("getMappingMap") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .returns(mMappingList) .addStatement("return mMappingMap") .build(); MethodSpec hostMethod = MethodSpec.methodBuilder("getHost") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .returns(controllerType) .addStatement("return mHost") .build(); String adapterPackageName = getPackageName(type).getQualifiedName().toString(); String className = String.format("%sAdapter", type.getSimpleName()); TypeSpec adapterClass = TypeSpec.classBuilder(className) .addJavadoc(Constants.DOC_EDIT_WARN) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .superclass(mMappingAdapter) .addField(hostField) .addField(mappingField) .addMethod(rootMethod) .addMethod(mappingMethod) .addMethod(hostMethod) .build(); JavaFile javaFile = JavaFile.builder(adapterPackageName, adapterClass).build(); try { javaFile.writeTo(mFiler); } catch (IOException e) { throw new RuntimeException(e); } String group = getGroup(type); List<String> adapterList = adapterMap.get(group); if (CollectionUtils.isEmpty(adapterList)) { adapterList = new ArrayList<>(); adapterMap.put(group, adapterList); } adapterList.add(adapterPackageName + "." + className); } if (!adapterMap.isEmpty()) { createRegister(registerPackageName, adapterMap); } }