本文整理汇总了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();
}
}
示例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;
}
}
示例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;
}
示例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;
}
}
示例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;
}
示例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();
}
示例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);
}
}
示例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);
}
}
示例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();
}
}
示例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;
}
示例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);
}
}
示例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);
}
示例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();
}
}
示例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();
}
}
示例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());
}