本文整理匯總了Java中javax.tools.JavaFileObject.openWriter方法的典型用法代碼示例。如果您正苦於以下問題:Java JavaFileObject.openWriter方法的具體用法?Java JavaFileObject.openWriter怎麽用?Java JavaFileObject.openWriter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類javax.tools.JavaFileObject
的用法示例。
在下文中一共展示了JavaFileObject.openWriter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: writeSourceFile
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
private void writeSourceFile(String className, String text, TypeElement originatingType) {
try {
JavaFileObject sourceFile =
processingEnv.getFiler().createSourceFile(className, originatingType);
Writer writer = sourceFile.openWriter();
try {
writer.write(text);
} finally {
writer.close();
}
} catch (IOException e) {
// This should really be an error, but we make it a warning in the hope of resisting Eclipse
// bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=367599. If that bug manifests, we may get
// invoked more than once for the same file, so ignoring the ability to overwrite it is the
// right thing to do. If we are unable to write for some other reason, we should get a compile
// error later because user code will have a reference to the code we were supposed to
// generate (new AutoValue_Foo() or whatever) and that reference will be undefined.
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
"Could not write generated class " + className + ": " + e);
}
}
示例2: process
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Map<String, Integer> map = new HashMap<>();
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(ContentView.class);
for (Element element : elements) {
TypeElement type = (TypeElement) element;
ContentView annotation = type.getAnnotation(ContentView.class);
String name = type.getQualifiedName().toString();
map.put(name, annotation.value());
}
try {
JavaFileObject sourceFile = filer.createSourceFile(API_PATH);
Writer writer = sourceFile.openWriter();
writer.write(generateCode(map));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
示例3: printSource
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
/** Emit plain Java source for a class.
* @param env The attribution environment of the outermost class
* containing this class.
* @param cdef The class definition to be printed.
*/
JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
JavaFileObject outFile
= fileManager.getJavaFileForOutput(CLASS_OUTPUT,
cdef.sym.flatname.toString(),
JavaFileObject.Kind.SOURCE,
null);
if (inputFiles.contains(outFile)) {
log.error(cdef.pos(), Errors.SourceCantOverwriteInputFile(outFile));
return null;
} else {
try (BufferedWriter out = new BufferedWriter(outFile.openWriter())) {
new Pretty(out, true).printUnit(env.toplevel, cdef);
if (verbose)
log.printVerbose("wrote.file", outFile);
}
return outFile;
}
}
示例4: printSource
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
/**
* Emit plain Java source for a class.
*
* @param env The attribution environment of the outermost class
* containing this class.
* @param cdef The class definition to be printed.
*/
JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
JavaFileObject outFile
= fileManager.getJavaFileForOutput(CLASS_OUTPUT,
cdef.sym.flatname.toString(),
JavaFileObject.Kind.SOURCE,
null);
if (inputFiles.contains(outFile)) {
log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
return null;
} else {
BufferedWriter out = new BufferedWriter(outFile.openWriter());
try {
new Pretty(out, true).printUnit(env.toplevel, cdef);
if (verbose)
log.printVerbose("wrote.file", outFile);
} finally {
out.close();
}
return outFile;
}
}
示例5: createFile
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
/**
* create the real file to be compiled
*/
private void createFile(String packageName, String enclosingName, String[] permissions, String methodName, String returnType) {
try {
Calendar calendar = Calendar.getInstance();
String classPostfix = "" + (calendar.get(Calendar.MINUTE) + 100) + (calendar.get(Calendar.SECOND) + 100) + (calendar.get(Calendar.MILLISECOND) + 1000);
JavaFileObject jfo = mFiler.createSourceFile(packageName + ".AutoCreate" + classPostfix, new Element[]{});
Writer writer = jfo.openWriter();
if ("void".equals(returnType)) {
writer.write(CodeCreator.brewCode(packageName, enclosingName, permissions, classPostfix, methodName, returnType));
} else {
writer.write(CodeCreator.brewCodeNoCallback(packageName, enclosingName, permissions, classPostfix, methodName, returnType));
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
示例6: printSource
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
/** Emit plain Java source for a class.
* @param env The attribution environment of the outermost class
* containing this class.
* @param cdef The class definition to be printed.
*/
JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
JavaFileObject outFile
= fileManager.getJavaFileForOutput(CLASS_OUTPUT,
cdef.sym.flatname.toString(),
JavaFileObject.Kind.SOURCE,
null);
if (inputFiles.contains(outFile)) {
log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
return null;
} else {
BufferedWriter out = new BufferedWriter(outFile.openWriter());
try {
new Pretty(out, true).printUnit(env.toplevel, cdef);
if (verbose)
log.printVerbose("wrote.file", outFile);
} finally {
out.close();
}
return outFile;
}
}
示例7: createSourceFile
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
private void createSourceFile(ClassGeneratingParams classGeneratingParams) {
try {
JavaFileObject f = processingEnv.getFiler().createSourceFile(classGeneratingParams.getName());
Writer w = f.openWriter();
w.write(classGeneratingParams.getBody());
w.flush();
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
示例8: createSourceFile
import javax.tools.JavaFileObject; //導入方法依賴的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);
}
}
示例9: writeJavaFile
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
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;
}
}
示例10: generateCode
import javax.tools.JavaFileObject; //導入方法依賴的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();
}
示例11: writeDataClassFor
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
private void writeDataClassFor(TypeElement clazz) throws IOException {
String builderClassName = clazz.getSimpleName() + "Data";
String builderFileName = clazz.getQualifiedName() + "Data";
PackageElement packageElement = (PackageElement) clazz.getEnclosingElement();
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(builderClassName)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
copyAnnotations(clazz, classBuilder);
VariableElement[] fieldElements = getFieldElements(clazz);
if (fieldElements.length != 0) {
classBuilder.addMethod(buildConstructorSpec(fieldElements));
for (VariableElement fieldElement : fieldElements) {
classBuilder.addField(buildField(fieldElement));
classBuilder.addMethod(buildGetterSpec(fieldElement));
classBuilder.addMethod(buildSetterSpec(fieldElement));
}
classBuilder.addMethod(buildHashcodeSpec(fieldElements));
classBuilder.addMethod(buildEqualsSpec(fieldElements, builderClassName));
}
JavaFile javaFile = JavaFile
.builder(packageElement.getQualifiedName().toString(), classBuilder.build())
.build();
JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderFileName);
try (PrintWriter out = new PrintWriter(builderFile.openWriter())) {
javaFile.writeTo(out);
}
}
示例12: createPluginFactory
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
private static void createPluginFactory(ProcessingEnvironment env, Element topLevelClass, List<GeneratedPlugin> plugins) {
PackageElement pkg = (PackageElement) topLevelClass.getEnclosingElement();
String genClassName = "PluginFactory_" + topLevelClass.getSimpleName();
try {
JavaFileObject factory = env.getFiler().createSourceFile(pkg.getQualifiedName() + "." + genClassName, topLevelClass);
try (PrintWriter out = new PrintWriter(factory.openWriter())) {
out.printf("// CheckStyle: stop header check\n");
out.printf("// CheckStyle: stop line length check\n");
out.printf("// GENERATED CONTENT - DO NOT EDIT\n");
out.printf("// GENERATORS: %s, %s\n", VerifierAnnotationProcessor.class.getName(), PluginGenerator.class.getName());
out.printf("package %s;\n", pkg.getQualifiedName());
out.printf("\n");
createImports(out, plugins);
out.printf("\n");
out.printf("@ServiceProvider(NodeIntrinsicPluginFactory.class)\n");
out.printf("public class %s implements NodeIntrinsicPluginFactory {\n", genClassName);
for (GeneratedPlugin plugin : plugins) {
out.printf("\n");
plugin.generate(env, out);
}
out.printf("\n");
createPluginFactoryMethod(out, plugins);
out.printf("}\n");
}
} catch (IOException e) {
env.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
}
}
示例13: writeJsonWriterClass
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
private void writeJsonWriterClass(Element element, Scope scope) throws IOException {
Filer filer = processingEnv.getFiler();
JavaFileObject fileObject = filer.createSourceFile(scope.getTargetClassNameWithPackage(), element);
try (Writer writer = fileObject.openWriter()) {
template.execute(writer, scope);
}
}
示例14: writeDtoClass
import javax.tools.JavaFileObject; //導入方法依賴的package包/類
/**
* Write Dto class to disk
*
* @param queryDesc description of query
* @param isReq write request (true) or response (false)
* @param baseDtoClassName name of parent dto class
*/
private void writeDtoClass(
QueryDesc queryDesc,
boolean isReq,
String baseDtoClassName
) {
if (isReq && CollectionUtils.isEmpty(queryDesc.getRequestParamList())
|| !isReq && CollectionUtils.isEmpty(queryDesc.getResponseParamList())) {
return;
}
try {
VelocityContext context = new VelocityContext();
context.put("fields", isReq ? queryDesc.getRequestParamList() : queryDesc.getResponseParamList());
String methodNameUpper = StringUtils.capitalize(queryDesc.getMethodName());
String dtoClassName = methodNameUpper + (isReq ? "Req" : "Res");
String packageName = queryDesc.getPackageName() + ".dto";
List<String> implementsList = isReq ? queryDesc.getReqImplementsList() : queryDesc.getResImplementsList();
processImplementsList(context, new HashSet<>(implementsList));
context.put("dtoClassName", dtoClassName);
context.put("classPackage", packageName);
context.put("classJavadoc", queryDesc.getClassJavadoc());
context.put("baseDtoClass", baseDtoClassName);
JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(packageName + "." + dtoClassName);
try (PrintWriter writer = new PrintWriter(builderFile.openWriter())) {
Template template = Velocity.getTemplate("dto-class-template.vm", MiscUtils.UTF_8);
template.merge(context, writer);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
示例15: createSourceFile
import javax.tools.JavaFileObject; //導入方法依賴的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);
}
}