当前位置: 首页>>代码示例>>Java>>正文


Java Filer.createSourceFile方法代码示例

本文整理汇总了Java中javax.annotation.processing.Filer.createSourceFile方法的典型用法代码示例。如果您正苦于以下问题:Java Filer.createSourceFile方法的具体用法?Java Filer.createSourceFile怎么用?Java Filer.createSourceFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.annotation.processing.Filer的用法示例。


在下文中一共展示了Filer.createSourceFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: toJavaFile

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
public static void toJavaFile(Filer filer, Builder classBuilder, ClassName className,
    TypeElement... originatingElement)
{
    try
    {
        JavaFile javaFile =
            JavaFile.builder(className.packageName(), classBuilder.build()).build();

        JavaFileObject javaFileObject =
            filer.createSourceFile(className.reflectionName(), originatingElement);

        Writer writer = javaFileObject.openWriter();
        javaFile.writeTo(writer);
        writer.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
 
开发者ID:Axellience,项目名称:vue-gwt,代码行数:21,代码来源:GenerationUtil.java

示例2: writeTo

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
/**
 * Writes this to {@code filer}.
 */
public void writeTo(Filer filer)
        throws IOException
{
    String fileName = packageName.isEmpty()
            ? typeSpec.name
            : packageName + "." + typeSpec.name;
    List<Element> originatingElements = typeSpec.originatingElements;
    JavaFileObject filerSourceFile = filer.createSourceFile(fileName,
            originatingElements.toArray(new Element[originatingElements.size()]));
    try (Writer writer = filerSourceFile.openWriter()) {
        writeTo(writer);
    }
    catch (Exception e) {
        try {
            filerSourceFile.delete();
        }
        catch (Exception ignored) {
        }
        throw e;
    }
}
 
开发者ID:wrmsr,项目名称:wava,代码行数:25,代码来源:JavaFile.java

示例3: getProjectRoot

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
private File getProjectRoot() throws Exception {
    if (projectRoot == null) {
        Filer filer = processingEnv.getFiler();

        JavaFileObject dummySourceFile = filer.createSourceFile("dummy" + System.currentTimeMillis());

        String dummySourceFilePath = dummySourceFile.toUri().toString();

        if (dummySourceFilePath.startsWith("file:")) {
            if (!dummySourceFilePath.startsWith("file://")) {
                dummySourceFilePath = "file://" + dummySourceFilePath.substring("file:".length());
            }
        } else {
            dummySourceFilePath = "file://" + dummySourceFilePath;
        }

        URI cleanURI = new URI(dummySourceFilePath);

        File dummyFile = new File(cleanURI);

        projectRoot = dummyFile.getParentFile();
    }

    return projectRoot;
}
 
开发者ID:FabianTerhorst,项目名称:FastLayout,代码行数:26,代码来源:LayoutProcessor.java

示例4: writeTo

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
/** Writes this to {@code filer}. */
public void writeTo(Filer filer) throws IOException {
  String fileName = packageName.isEmpty()
      ? typeSpec.name
      : packageName + "." + typeSpec.name;
  List<Element> originatingElements = typeSpec.originatingElements;
  JavaFileObject filerSourceFile = filer.createSourceFile(fileName,
      originatingElements.toArray(new Element[originatingElements.size()]));
  try (Writer writer = filerSourceFile.openWriter()) {
    writeTo(writer);
  } catch (Exception e) {
    try {
      filerSourceFile.delete();
    } catch (Exception ignored) {
    }
    throw e;
  }
}
 
开发者ID:Ufkoku,项目名称:AndroidMVPHelper,代码行数:19,代码来源:JavaFile.java

示例5: generteSrcFile

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
public static String generteSrcFile( Filer filer, EntityInfo entityInfo ) {
    String pkgName = entityInfo.getBinName().toString();
    pkgName = pkgName.substring(0, pkgName.lastIndexOf('.'));

    TypeName typeName = TypeName.get(entityInfo.getTypeElement().asType());

    String objName = "obj" + entityInfo.getTypeElement().getSimpleName();
    MethodSpec.Builder methodBronObject = createBronObjectMethod(typeName, objName);
    MethodSpec.Builder methodGetObject = createGetObjectMethod(typeName, objName, entityInfo);

    MethodSpec.Builder methodSetObject = createSetObjectMethod(typeName, objName, entityInfo);

    MethodSpec.Builder methodGetPkType = createGetPkTypeMethod(entityInfo);

    MethodSpec.Builder methodGetTableName = MethodSpec.methodBuilder("getTableName")
            .returns(TypeName.get(String.class))
            .addParameter(Class.class, "classOf", Modifier.FINAL).addModifiers(Modifier.PUBLIC);
    methodGetTableName.addStatement("return $S", entityInfo.getTableName());

    MethodSpec.Builder methodGetPkName = createGetPkNamesMethod(entityInfo);

    MethodSpec.Builder methodGetPkNameAndValues = createGetPKNameAndValueMethod(typeName,
            objName, entityInfo);

    MethodSpec.Builder methodCreateSql = CreateGetCreateSqlMethod(entityInfo);

    TypeSpec.Builder build = TypeSpec.classBuilder(
            entityInfo.getBinName().replace(pkgName, "").substring(1) + "Adapter")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    ClassName recordAdapterName = ClassName.get(Constants.IMPL_PKGNAME, "RecordAdapter");
    ClassName entityName = ClassName.get(pkgName, typeName.toString());
    build.superclass(ParameterizedTypeName.get(recordAdapterName, entityName));
    build.addMethod(methodBronObject.build());
    build.addMethod(methodGetObject.build());
    build.addMethod(methodSetObject.build());
    build.addMethod(methodCreateSql.build());
    build.addMethod(methodGetPkType.build());
    build.addMethod(methodGetPkName.build());
    build.addMethod(methodGetTableName.build());
    build.addMethod(methodGetPkNameAndValues.build());
    build.addMethod(createGetOneLinktMethod(typeName, objName, entityInfo).build());
    build.addMethod(createGetManyLinktMethod(typeName, objName, entityInfo).build());
    JavaFile javaFile = JavaFile.builder(pkgName, build.build()).build();

    try {
        JavaFileObject file = filer.createSourceFile(entityInfo.getBinName() + "Adapter",
                entityInfo.getTypeElement());
        Writer witrer = file.openWriter();
        javaFile.writeTo(witrer);
        witrer.flush();
        witrer.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException();
    }
    return pkgName + "." + javaFile.typeSpec.name;

}
 
开发者ID:joker535,项目名称:sorm,代码行数:59,代码来源:EntityCodeGenertor.java

示例6: generateCode

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
public void generateCode(Elements elementUtils, Filer filer) throws IOException {
    TypeElement superClassName = elementUtils.getTypeElement(qualifiedClassName);
    String factoryClassName = superClassName.getSimpleName() + SUFFIX;

    JavaFileObject jfo = filer.createSourceFile(qualifiedClassName + SUFFIX);
    Writer writer = jfo.openWriter();
    JavaWriter jw = new JavaWriter(writer);

    // 写包名
    PackageElement pkg = elementUtils.getPackageOf(superClassName);
    if (!pkg.isUnnamed()) {
        jw.emitPackage(pkg.getQualifiedName().toString());
        jw.emitEmptyLine();
    } else {
        jw.emitPackage("");
    }

    jw.beginType(factoryClassName, "class", EnumSet.of(Modifier.PUBLIC));
    jw.emitEmptyLine();
    jw.beginMethod(qualifiedClassName, "create", EnumSet.of(Modifier.PUBLIC), "String", "id");

    jw.beginControlFlow("if (id == null)");
    jw.emitStatement("throw new IllegalArgumentException(\"id is null!\")");
    jw.endControlFlow();

    for (FactoryAnnotatedClass item : itemsMap.values()) {
        jw.beginControlFlow(String.format("if (\"%s\".equals(id))", item.getId()));
        jw.emitStatement("return new %s()", item.getTypeElement().getQualifiedName().toString());
        jw.endControlFlow();
        jw.emitEmptyLine();
    }

    jw.emitStatement("throw new IllegalArgumentException(\"Unknown id = \" + id)");
    jw.endMethod();
    jw.endType();
    jw.close();
}
 
开发者ID:jacklongway,项目名称:FactoryAnnotation,代码行数:38,代码来源:FactoryGroupedClasses.java

示例7: createSourceFile

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
protected PrintWriter createSourceFile(String pkg, String relativeName, Filer filer, Element... originatingElements) {
    try {
        // Ensure Unix line endings to comply with code style guide checked by Checkstyle
        JavaFileObject sourceFile = filer.createSourceFile(pkg + "." + relativeName, originatingElements);
        return new PrintWriter(sourceFile.openWriter()) {

            @Override
            public void println() {
                print("\n");
            }
        };
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:16,代码来源:OptionProcessor.java

示例8: createSourceFile

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
protected PrintWriter createSourceFile(String pkg, String relativeName, Filer filer, Element... originatingElements) {
    try {
        // Ensure Unix line endings to comply with Graal code style guide checked by Checkstyle
        JavaFileObject sourceFile = filer.createSourceFile(pkg + "." + relativeName, originatingElements);
        return new PrintWriter(sourceFile.openWriter()) {

            @Override
            public void println() {
                print("\n");
            }
        };
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:16,代码来源:MatchProcessor.java

示例9: writeFile

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
void writeFile(Filer filer, String packageName, String name, Template template, Object dataModel) throws IOException {
    JavaFileObject file = filer.createSourceFile(packageName + "." + name);
    Writer writer = file.openWriter();
    try {
        template.process(dataModel, writer);
    } catch (TemplateException err) {
        throw new IOException(err);
    } finally {
        writer.close();
    }
}
 
开发者ID:lifechurch,项目名称:nuclei-android,代码行数:12,代码来源:Context.java

示例10: createFile

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
/**
 * create a Java source file
 *
 * @return
 */
protected JavaFileObject createFile() {
    JavaFileObject result = null;
    Filer filer = processingEnvironment.getFiler();
    try {
        result = filer.createSourceFile(getModelClassName());
    } catch (IOException e) {
        logger.log(Diagnostic.Kind.ERROR, "create source file failed");
        e.printStackTrace();
    }
    return result;
}
 
开发者ID:simplify20,项目名称:PowerfulRecyclerViewAdapter,代码行数:17,代码来源:BaseViewGenerator.java

示例11: internalCreateSourceFile

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
private void internalCreateSourceFile(String packageName, ClassName templateQualifiedClassName, ClassName generatedQualifiedClassName, String annotationType, TypeSpec.Builder builder, TypeElement element)
{
    AnnotationSpec generated = AnnotationSpec
        .builder(Generated.class)
        .addMember("value", "\"" + annotationType + "\"")
        .build();
    builder.addAnnotation(generated);

    TypeSpec classSpec = builder.build();
    JavaFile javaFile = JavaFile.builder(packageName, classSpec)
        .addFileComment("Auto generated from $L by Soabase " + annotationType + " annotation processor", templateQualifiedClassName)
        .indent("    ")
        .build();

    Filer filer = processingEnv.getFiler();
    try
    {
        JavaFileObject sourceFile = filer.createSourceFile(generatedQualifiedClassName.toString());
        try ( Writer writer = sourceFile.openWriter() )
        {
            javaFile.writeTo(writer);
        }
    }
    catch ( IOException e )
    {
        String message = "Could not create source file";
        if ( e.getMessage() != null )
        {
            message = message + ": " + e.getMessage();
        }
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element);
    }
}
 
开发者ID:soabase,项目名称:soabase-halva,代码行数:34,代码来源:MasterProcessor.java

示例12: createSourceFile

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
public static JavaFileObject createSourceFile(
    final TypeElement baseElement, final String packageName, final String className
) throws Exception {
    final ProcessingEnvironment env = ProcessorContextHolder.getProcessingEnvironment();
    final Filer filer = env.getFiler();

    return filer.createSourceFile(packageName + SourceTextUtils.PACKAGE_SEPARATOR + className, baseElement);
}
 
开发者ID:vbauer,项目名称:jackdaw,代码行数:9,代码来源:ProcessorUtils.java

示例13: generate

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
public void generate(Filer filer,
					 Element lastElement,
					 List<String> annotatedClasses,
					 List<String> parcelerNames) {
	try {

		String packageName = FrameworkUtil.getEasyParcelPackageName();
		String className = FrameworkUtil.getParcelerListImplClassName();
		String innerClassName = className + "Inner";

		JavaFileObject jfo = filer.createSourceFile(packageName + "." + className, lastElement);
		Writer writer = jfo.openWriter();
		EzpJavaWriter jw = new EzpJavaWriter(writer);
		jw.emitPackage(packageName);
		jw.emitImports("java.util.Map");
		jw.emitImports("java.util.HashMap");
		jw.emitImports("java.util.Set");
		jw.emitImports("android.os.Parcelable");
		jw.emitImports(FrameworkUtil.getQualifiedName(FrameworkUtil.getParcelerClassName()));
		jw.emitImports(FrameworkUtil.getQualifiedName(FrameworkUtil.getParcelablesClassName()));
		jw.emitImports(FrameworkUtil.getQualifiedName(FrameworkUtil.getParcelerListClassName()));
		jw.emitEmptyLine();

		jw.emitJavadoc("Generated class by @%s . Do not modify this code!",
				EasyParcel.class.getSimpleName());
		jw.beginType(className, "class", EnumSet.of(Modifier.PUBLIC), null);
		jw.emitEmptyLine();

		jw.beginType(innerClassName, "class", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC),
				null, FrameworkUtil.getParcelerListClassName());
		jw.emitField("Map<Class<? extends Parcelable>, " + FrameworkUtil.getParcelerClassName() + ">", "map");
		jw.beginConstructor(EnumSet.of(Modifier.PUBLIC));
		jw.emitStatement("map = new HashMap<>()");
		for (int i = 0; i < annotatedClasses.size(); i++) {
			jw.emitStatement("map.put(" + annotatedClasses.get(i) + ".class, new " + parcelerNames.get(i) + "())");
		}
		jw.emitStatement(FrameworkUtil.getParcelablesClassName() + ".setParcelerList(this)");
		jw.endConstructor();

		jw.beginMethod("<T extends Parcelable> " + FrameworkUtil.getParcelerClassName() + "<T>",
				"getParcelerForClass",
				EnumSet.of(Modifier.PUBLIC), "Class<T>", "clazz");
		jw.emitStatement("return map.get(clazz)");
		jw.endMethod();

		jw.beginMethod("Set<Class<? extends Parcelable>>", "getAllClasses", EnumSet.of(Modifier.PUBLIC));
		jw.emitStatement("return map.keySet()");
		jw.endMethod();

		jw.endType();

		jw.emitField(innerClassName, "INSTANCE", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL),
				"new " + innerClassName + "()");


		jw.endType();
		jw.close();

	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
开发者ID:globulus,项目名称:easyparcel,代码行数:63,代码来源:ParcelerListCodeGen.java

示例14: generateCode

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
/**
 * Generates the code for our "Sensor Binder" class and writes it to the same package as the
 * annotated class.
 *
 * @param groupedMethodsMap Map of annotated methods per class.
 * @param elementUtils ElementUtils class from {@link ProcessingEnvironment}.
 * @param filer File writer class from {@link ProcessingEnvironment}.
 * @throws IOException
 * @throws ProcessingException
 */
static void generateCode(@NonNull Map<String, AnnotatedMethodsPerClass> groupedMethodsMap,
    @NonNull Elements elementUtils, @NonNull Filer filer)
    throws IOException, ProcessingException {
    for (AnnotatedMethodsPerClass groupedMethods : groupedMethodsMap.values()) {
        // If we've annotated methods in an activity called "ExampleActivity" then that will be
        // the enclosing type element.
        TypeElement enclosingClassTypeElement =
            elementUtils.getTypeElement(groupedMethods.getEnclosingClassName());

        // Create the parameterized type that our generated class will implement,
        // (such as "SensorBinder<ExampleActivity>").
        ParameterizedTypeName parameterizedInterface = ParameterizedTypeName.get(SENSOR_BINDER,
            TypeName.get(enclosingClassTypeElement.asType()));

        // Create the target parameter that will be used in the constructor and bind method,
        // (such as "ExampleActivity").
        ParameterSpec targetParameter =
            ParameterSpec.builder(TypeName.get(enclosingClassTypeElement.asType()), "target")
                .addModifiers(Modifier.FINAL)
                .build();

        MethodSpec constructor =
            createConstructor(targetParameter, groupedMethods.getItemsMap());
        MethodSpec bindMethod = createBindMethod(targetParameter, groupedMethods);

        TypeSpec sensorBinderClass =
            TypeSpec.classBuilder(enclosingClassTypeElement.getSimpleName() + SUFFIX)
                .addModifiers(Modifier.FINAL)
                .addSuperinterface(parameterizedInterface)
                .addField(SENSOR_MANAGER_FIELD)
                .addField(LISTENER_WRAPPERS_FIELD)
                .addMethod(constructor)
                .addMethod(bindMethod)
                .addMethod(UNBIND_METHOD)
                .build();

        // Output our generated file with the same package as the target class.
        PackageElement packageElement = elementUtils.getPackageOf(enclosingClassTypeElement);
        JavaFileObject jfo =
            filer.createSourceFile(enclosingClassTypeElement.getQualifiedName() + SUFFIX);
        Writer writer = jfo.openWriter();
        JavaFile.builder(packageElement.toString(), sensorBinderClass)
            .addFileComment("This class is generated code from Sensor Lib. Do not modify!")
            .addStaticImport(CONTEXT, "SENSOR_SERVICE")
            .build()
            .writeTo(writer);
        writer.close();
    }
}
 
开发者ID:dvoiss,项目名称:SensorAnnotations,代码行数:60,代码来源:SensorAnnotationsFileBuilder.java

示例15: PreferenceHolder

import javax.annotation.processing.Filer; //导入方法依赖的package包/类
public PreferenceHolder(TypeElement element, Filer filer, Messager messager) throws IOException {
    this.mElement = element;

    // Set the name of the file / class and nested editor
    SharedPreference sharedPreference = mElement.getAnnotation(SharedPreference.class);
    final String name = (sharedPreference.value().equals(SharedPreference.EMPTY)) ? mElement.getSimpleName().toString()
            : sharedPreference.value();
    mClassName = name + sharedPreference.preferencesSuffix();
    mEditorName = name + sharedPreference.editorSuffix();
    mIsCustomPackage = !sharedPreference.packagename().equals(SharedPreference.EMPTY);
    mPackageName = mIsCustomPackage ? sharedPreference.packagename() :
            ((PackageElement) element.getEnclosingElement()).getQualifiedName().toString();

    // Check validity of package / class names.
    if (!checkValidIdentifier(mPackageName))
        throw new IOException(mPackageName + " is not a valid packagename");
    if (!checkValidIdentifier(mClassName))
        throw new IOException(mClassName + " is not a valid class name");
    if (!checkValidIdentifier(mEditorName))
        throw new IOException(mEditorName + " is not a valid class name");

    // set the name of the sharedPreferences created with the context
    DefaultPreferenceName defName = element.getAnnotation(DefaultPreferenceName.class);
    if (defName != null)
        preferencesName = defName.value();
    else
        preferencesName = DEFAULT_PREFERENCES_NAME;

    // default type if not specified
    DefaultPreferenceType defType = element.getAnnotation(DefaultPreferenceType.class);
    final PreferenceType defaultPreferenceType;
    if (defType != null)
        defaultPreferenceType = defType.value();
    else
        defaultPreferenceType = null;

    Set<String> preferenceIds = new LinkedHashSet<>();
    for (Element e : element.getEnclosedElements()) {
        if (!e.getKind().isField()) {
            messager.printMessage(Diagnostic.Kind.WARNING, e.getSimpleName() + " is not a field", e);
            continue;
        }
        VariableElement var = (VariableElement) e;
        if (!var.asType().toString().equals("java.lang.String")) {
            messager.printMessage(Diagnostic.Kind.WARNING, var.asType().toString() + " is not of type String", e);
            continue;
        }
        if (var.getConstantValue() == null) {
            messager.printMessage(Diagnostic.Kind.ERROR, var.getSimpleName() + " is not final or no value is set", e);
            continue;
        }
        final String fieldName = var.getSimpleName().toString();
        final String accessorName = Preference.camelCaseName(fieldName);
        Preference old = preferences.get(accessorName);
        if (old != null) {
            messager.printMessage(Diagnostic.Kind.WARNING, accessorName + " used here is ignored", var);
            messager.printMessage(Diagnostic.Kind.WARNING, "because it was already defined here", old.getElement());
            continue;
        }
        final String id = var.getConstantValue().toString();
        if (!preferenceIds.add(id))
            messager.printMessage(Diagnostic.Kind.WARNING, "preference key " + id + " is already in use");
        preferences.put(accessorName, new Preference(fieldName, accessorName, id, var, defaultPreferenceType));
    }

    JavaFileObject jfo = filer.createSourceFile(mPackageName + "." + mClassName);
    this.mWriter = new JavaWriter(jfo.openWriter());
}
 
开发者ID:bleeding182,项目名称:sharedpreferences-annotations,代码行数:69,代码来源:PreferenceHolder.java


注:本文中的javax.annotation.processing.Filer.createSourceFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。