本文整理汇总了Java中javax.annotation.processing.AbstractProcessor类的典型用法代码示例。如果您正苦于以下问题:Java AbstractProcessor类的具体用法?Java AbstractProcessor怎么用?Java AbstractProcessor使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
AbstractProcessor类属于javax.annotation.processing包,在下文中一共展示了AbstractProcessor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: compile
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
private void compile(Class<? extends AbstractProcessor> processorClass, List<String> classes) throws IOException {
List<String> options = new ArrayList<String>();
options.add("-s");
options.add("src/test/java");
options.add("-proc:only");
options.add("-processor");
options.add(processorClass.getName());
options.add("-sourcepath");
options.add("src/test/java");
options.addAll(getAPTOptions());
options.addAll(classes);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
int compilationResult = compiler.run(null, out, err, options.toArray(new String[options.size()]));
// Processor.elementCache.clear();
if (compilationResult != 0) {
Assert.fail("Compilation Failed:\n " + new String(err.toByteArray(), "UTF-8"));
}
}
示例2: testEnclosingMethod
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
/**
* Test that the ijar tool preserves EnclosingMethod attributes and doesn't
* prevent annotation processors from accessing all the elements in a package.
*/
@Test
public void testEnclosingMethod() throws IOException {
JavaCompiler.CompilationTask task = makeCompilationTask("third_party/ijar/test/package-info.java");
task.setProcessors(Arrays.asList(new AbstractProcessor() {
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton("*");
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
roundEnv.getElementsAnnotatedWith(java.lang.Override.class);
return true;
}
}));
if (!task.call()) {
fail(getFailedCompilationMessage());
}
}
示例3: generateInfoClasses
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
public boolean generateInfoClasses(AbstractProcessor processor, List<Class<?>> sourceClasses)
throws Exception {
ImmutableSet<? extends AbstractProcessor> processors = ImmutableSet.of(processor);
List<Diagnostic<? extends JavaFileObject>> diagnostics = compileWithProcessors(
sourceClasses,
processors
);
boolean failed = false;
for (Diagnostic<?> diagnostic : diagnostics) {
failed = failed | (diagnostic.getKind().equals(Kind.ERROR));
System.out.println(String.format("[%s] %s [%s,%s]",
diagnostic.getKind(), diagnostic.getMessage(Locale.getDefault()),
diagnostic.getLineNumber(), diagnostic.getColumnNumber()
));
}
return failed;
}
示例4: testModelInfoClassGeneration
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
@Test
public void testModelInfoClassGeneration() throws Exception {
AbstractProcessor fieldNameProcessor = createFieldNameProcessor(outputClasses);
// TODO hacky - can this be avoided?
MetaApiInfoClassGenerator.addPath("./src/test/java/");
boolean hasFailed = generator.generateInfoClasses(fieldNameProcessor, sourceClasses);
assertFalse("generation of model info classes failed", hasFailed);
File file;
for (Class<?> outputClass : outputClasses) {
file = new File(filePathFrom(outputClass));
assertTrue("file "
+ outputClass.getSimpleName()
+ "Info.java should exist but does not", file.exists());
}
}
示例5: createFieldNameProcessor
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
private AbstractProcessor createFieldNameProcessor(Iterable<Class<?>> classesToOutput) {
SourceGenerator<ModelTypeInfo, ModelMethodInfo> classGenerator = new ModelClassInfoSourceGenerator();
HierarchyExtractor hierarchyExtractor = new ReflectionBasedHierarchyExtractor();
SourceFileWriter<ModelTypeInfo> writer = new JavaxSourceFileWriter<>();
TypeParser<ModelTypeInfo, ModelMethodInfo> typeParser = new ModelTypeParser(
javadocParser,
classesToOutput
);
return new FieldNameProcessor(
classGenerator,
hierarchyExtractor,
writer,
typeParser,
classesToOutput
);
}
示例6: testModelInfoClassGeneration
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
@Test
public void testModelInfoClassGeneration() throws Exception {
AbstractProcessor fieldNameProcessor = createFieldNameProcessor(sourceClasses);
// TODO hacky - can this be avoided?
MetaApiInfoClassGenerator.addPath("./src/test/java/");
boolean hasFailed = generator.generateInfoClasses(fieldNameProcessor, sourceClasses);
assertFalse("generation of model info classes failed", hasFailed);
File file;
for (Class<?> outputClass : sourceClasses) {
file = new File(filePathFrom(outputClass));
assertTrue("file "
+ outputClass.getSimpleName()
+ "EndpointInfo.java should exist but does not", file.exists());
}
}
示例7: check
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
protected void check() throws Exception {
String[] options = {
"--should-stop:at=ATTR",
"--debug:verboseResolution=success,failure,applicable,inapplicable,deferred-inference,predef"
};
AbstractProcessor[] processors = { new ResolveCandidateFinder(), null };
@SuppressWarnings("unchecked")
DiagnosticListener<? super JavaFileObject>[] diagListeners =
new DiagnosticListener[] { new DiagnosticHandler(false), new DiagnosticHandler(true) };
for (int i = 0 ; i < options.length ; i ++) {
JavacTask ct = (JavacTask)comp.getTask(null, fm, diagListeners[i],
Arrays.asList(options[i]), null, Arrays.asList(jfo));
if (processors[i] != null) {
ct.setProcessors(Collections.singleton(processors[i]));
}
ct.analyze();
}
//check diags
for (Diagnostic<? extends JavaFileObject> diag : diags) {
for (DiagnosticProcessor proc : diagProcessors) {
if (proc.matches(diag)) {
proc.process(diag);
break;
}
}
}
//check all candidates have been used up
for (Map.Entry<ElementKey, Candidate> entry : candidatesMap.entrySet()) {
if (!seenCandidates.contains(entry.getKey())) {
error("Redundant @Candidate annotation on method " + entry.getKey().elem + " sig = " + entry.getKey().elem.asType());
}
}
}
示例8: check
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
protected void check() throws Exception {
String[] options = {
"-XDshouldStopPolicy=ATTR",
"-XDverboseResolution=success,failure,applicable,inapplicable,deferred-inference,predef"
};
AbstractProcessor[] processors = { new ResolveCandidateFinder(), null };
@SuppressWarnings("unchecked")
DiagnosticListener<? super JavaFileObject>[] diagListeners =
new DiagnosticListener[] { new DiagnosticHandler(false), new DiagnosticHandler(true) };
for (int i = 0 ; i < options.length ; i ++) {
JavacTask ct = (JavacTask)comp.getTask(null, fm, diagListeners[i],
Arrays.asList(options[i]), null, Arrays.asList(jfo));
if (processors[i] != null) {
ct.setProcessors(Collections.singleton(processors[i]));
}
ct.analyze();
}
//check diags
for (Diagnostic<? extends JavaFileObject> diag : diags) {
for (DiagnosticProcessor proc : diagProcessors) {
if (proc.matches(diag)) {
proc.process(diag);
break;
}
}
}
//check all candidates have been used up
for (Map.Entry<ElementKey, Candidate> entry : candidatesMap.entrySet()) {
if (!seenCandidates.contains(entry.getKey())) {
error("Redundant @Candidate annotation on method " + entry.getKey().elem + " sig = " + entry.getKey().elem.asType());
}
}
}
示例9: createWrappedInstance
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
private static AbstractProcessor createWrappedInstance() {
ClassLoader cl = Main.createShadowClassLoader();
try {
Class<?> mc = cl.loadClass("lombok.core.AnnotationProcessor");
return (AbstractProcessor) mc.newInstance();
} catch (Throwable t) {
if (t instanceof Error) throw (Error) t;
if (t instanceof RuntimeException) throw (RuntimeException) t;
throw new RuntimeException(t);
}
}
示例10: assertProcess
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
static void assertProcess(BiConsumer<ProcessingEnvironment, RoundEnvironment> test) {
File f = null;
try {
f = Files.createTempFile("test", ".java").toFile();
try (PrintWriter writer = new PrintWriter(f)) {
writer.print("class Empty {}");
}
} catch (IOException e) {
throw new AssertionError(e);
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, Locale.getDefault(), Charset.defaultCharset());
JavaCompiler.CompilationTask task = compiler.getTask(new PrintWriter(System.out),
fileManager,
diagnostics,
Collections.singletonList("-proc:only"),
Collections.emptyList(),
fileManager.getJavaFileObjectsFromFiles(Collections.singletonList(f)));
task.setLocale(Locale.getDefault());
task.setProcessors(Collections.singleton(new AbstractProcessor() {
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton("*");
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
test.accept(processingEnv, roundEnv);
return true;
}
}));
assertTrue(task.call());
}
示例11: testGen
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
@Test
public void testGen() throws Exception {
AtomicInteger count = new AtomicInteger();
AbstractProcessor proc = new AbstractProcessor() {
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton("*");
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (count.getAndIncrement() == 0) {
try {
Filer filer = processingEnv.getFiler();
Element elt = processingEnv.getElementUtils().getTypeElement("gen.GeneratedClass");
JavaFileObject src = filer.createSourceFile("io.vertx.test.gen.GeneratedClass", elt);
try (Writer writer = src.openWriter()) {
writer.append("package io.vertx.test.gen;\npublic class GeneratedClass {\n}");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
};
Compiler<TestGenProcessor> compiler = buildCompiler(new TestGenProcessor(), "io.vertx.test.gen");
compiler.addProcessor(proc);
compiler.assertCompile();
assertEquals(3, count.get());
}
示例12: testCallbackIssuedAfterEnterWithAPs
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
@Test
public void testCallbackIssuedAfterEnterWithAPs() throws IOException {
// We add an unrelated source file here to make the compiler do something
compiler.addSourceFileContents("Bar.java", "class Bar { }");
compiler.setProcessors(
ImmutableList.of(
new AbstractProcessor() {
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton("*");
}
@Override
public boolean process(
Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
Filer filer = processingEnv.getFiler();
// We wait until the last possible momemt to generate Foo; if the callback is able to
// get an element for it, that means it ran after the enter phase
try (OutputStream outputStream =
filer.createSourceFile("Foo").openOutputStream()) {
outputStream.write("class Foo { }".getBytes());
} catch (IOException e) {
throw new AssertionError(e);
}
}
return false;
}
}));
addCallback("callback");
compiler.compile();
assertThat(callbacksIssued, Matchers.contains("callback: Bar, Foo"));
}
示例13: compileWithProcessors
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
private List<Diagnostic<? extends JavaFileObject>> compileWithProcessors(
Iterable<Class<?>> classes,
ImmutableSet<? extends AbstractProcessor> processors) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(
diagnosticCollector,
DEFAULT_LOCALE,
DEFAULT_CHARSET
);
Iterable<? extends JavaFileObject> sourceCompilationUnits = transformToCompilationUnits(
classes,
fileManager
);
CompilationTask task = compiler.getTask(new OutputStreamWriter(System.out),
fileManager, diagnosticCollector,
Arrays.asList(
"-proc:only",
"-s", "./src/main/java"
),
null,
sourceCompilationUnits
);
task.setProcessors(processors);
task.call();
try {
fileManager.close();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
return diagnosticCollector.getDiagnostics();
}
示例14: createFieldNameProcessor
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
private AbstractProcessor createFieldNameProcessor(Iterable<Class<?>> classesToOutput) {
SourceGenerator<EndpointTypeInfo, EndpointMethodInfo> classGenerator = new EndpointClassInfoSourceGenerator();
SourceFileWriter<EndpointTypeInfo> writer = new JavaxSourceFileWriter<>();
TypeParser<EndpointTypeInfo, EndpointMethodInfo> typeParser = new EndpointTypeParser(
javadocParser);
return new ControllerAnnotationProcessor(
classGenerator,
writer,
typeParser,
classesToOutput
);
}
示例15: processAnnotations
import javax.annotation.processing.AbstractProcessor; //导入依赖的package包/类
private JavaCompiler.CompilationTask processAnnotations(String[] testSourceFileNames, ElasticSearchDocumentAnnotationProcessor annotationProcessor) throws URISyntaxException {
// Get an instance of java compiler
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// Get a new instance of the standard file manager implementation
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
// Get the list of java file objects, in this case we have only
// one file, TestClass.java
// http://stackoverflow.com/a/676102/693752
List<File> listSourceFiles = new ArrayList<>();
for (String sourceFileName : testSourceFileNames) {
URL filename = ClassLoader.getSystemResource(sourceFileName);
listSourceFiles.add(new File(filename.toURI()));
}
Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(listSourceFiles);
// Create the compilation task
List<String> options = new ArrayList<>(Arrays.asList("-d", sandBoxDir.getAbsolutePath()));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits1);
if (annotationProcessor != null) {
// Create a list to hold annotation processors
LinkedList<AbstractProcessor> processors = new LinkedList<AbstractProcessor>();
// Add an annotation processor to the list
processors.add(annotationProcessor);
// Set the annotation processor to the compiler task
task.setProcessors(processors);
}
return task;
}
开发者ID:vossie,项目名称:elasticsearch-annotations,代码行数:34,代码来源:ElasticSearchDocumentAnnotationProcessorTest.java