當前位置: 首頁>>代碼示例>>Java>>正文


Java AbstractProcessor類代碼示例

本文整理匯總了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"));
        }
    }
 
開發者ID:HomoEfficio,項目名稱:spring-web-api-test-stubber,代碼行數:22,代碼來源:RestControllerProcessorTest.java

示例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());
  }
}
 
開發者ID:bazelbuild,項目名稱:bazel,代碼行數:24,代碼來源:IjarTests.java

示例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;
}
 
開發者ID:atlasapi,項目名稱:atlas-deer,代碼行數:20,代碼來源:MetaApiInfoClassGenerator.java

示例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());
    }
}
 
開發者ID:atlasapi,項目名稱:atlas-deer,代碼行數:19,代碼來源:FieldNameProcessorTest.java

示例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
    );
}
 
開發者ID:atlasapi,項目名稱:atlas-deer,代碼行數:18,代碼來源:FieldNameProcessorTest.java

示例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());
    }
}
 
開發者ID:atlasapi,項目名稱:atlas-deer,代碼行數:19,代碼來源:ProducesTypeProcessorTest.java

示例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());
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:38,代碼來源:ResolveHarness.java

示例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());
        }
    }
}
 
開發者ID:campolake,項目名稱:openjdk9,代碼行數:38,代碼來源:ResolveHarness.java

示例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);
	}
}
 
開發者ID:git03394538,項目名稱:lombok-ianchiu,代碼行數:12,代碼來源:AnnotationProcessor.java

示例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());
}
 
開發者ID:vert-x3,項目名稱:vertx-codegen,代碼行數:34,代碼來源:Utils.java

示例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());

}
 
開發者ID:vert-x3,項目名稱:vertx-docgen,代碼行數:34,代碼來源:BaseProcessorTest.java

示例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"));
}
 
開發者ID:facebook,項目名稱:buck,代碼行數:35,代碼來源:PostEnterTaskListenerTest.java

示例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();
}
 
開發者ID:atlasapi,項目名稱:atlas-deer,代碼行數:41,代碼來源:MetaApiInfoClassGenerator.java

示例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
    );
}
 
開發者ID:atlasapi,項目名稱:atlas-deer,代碼行數:14,代碼來源:ProducesTypeProcessorTest.java

示例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


注:本文中的javax.annotation.processing.AbstractProcessor類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。