javax.annotation.processing.AbstractProcessor#javax.tools.JavaCompiler源码实例Demo

下面列出了javax.annotation.processing.AbstractProcessor#javax.tools.JavaCompiler 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-jdk9   文件: DetectMutableStaticFields.java
private void run()
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor,
        URISyntaxException {

    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        for (String module: modules) {
            analyzeModule(fm, module);
        }
    }

    if (errors.size() > 0) {
        for (String error: errors) {
            System.err.println(error);
        }
        throw new AssertionError("There are mutable fields, "
            + "please check output");
    }
}
 
源代码2 项目: netbeans   文件: FileManagerTest.java
/** Crates the default javac file managare tro have something to comare 
    * our file managers against
    */
   public static JavaFileManager createGoldenJFM( File[] classpath, File[] sourcpath ) throws IOException {

JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
       StandardJavaFileManager fm = jc.getStandardFileManager (null, null, null);

if ( classpath != null ) {
           fm.setLocation(StandardLocation.CLASS_PATH,Arrays.asList(classpath));
}

if ( sourcpath != null ) {
    fm.setLocation(StandardLocation.SOURCE_PATH,Arrays.asList(sourcpath));
}

return fm;
	
   }
 
源代码3 项目: openjdk-jdk9   文件: T6852595.java
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
源代码4 项目: openjdk-jdk9   文件: ModuleInfoTreeAccess.java
@Test
public void testTreePathForModuleDecl(Path base) throws Exception {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path src = base.resolve("src");
        tb.writeJavaFiles(src, "/** Test module */ module m1x {}");

        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(findJavaFiles(src));
        JavacTask task = (JavacTask) compiler.getTask(null, fm, null, null, null, files);

        task.analyze();
        JavacTrees trees = JavacTrees.instance(task);
        ModuleElement mdle = (ModuleElement) task.getElements().getModuleElement("m1x");

        TreePath path = trees.getPath(mdle);
        assertNotNull("path", path);

        ModuleElement mdle1 = (ModuleElement) trees.getElement(path);
        assertNotNull("mdle1", mdle1);

        DocCommentTree docCommentTree = trees.getDocCommentTree(mdle);
        assertNotNull("docCommentTree", docCommentTree);
    }
}
 
源代码5 项目: openjdk-jdk9   文件: TestBootNativeLibraryPath.java
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
源代码6 项目: openjdk-jdk8u   文件: TestSelfRef.java
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

        for (EnclosingKind ek : EnclosingKind.values()) {
            for (SiteKind sk : SiteKind.values()) {
                if (sk == SiteKind.STATIC_INIT && ek == EnclosingKind.MEMBER_INNER)
                    continue;
                for (InnerKind ik : InnerKind.values()) {
                    if (ik != InnerKind.NONE && sk == SiteKind.NONE)
                        break;
                    for (RefKind rk : RefKind.values()) {
                        new TestSelfRef(ek, sk, ik, rk).run(comp, fm);
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
源代码7 项目: jdk8u60   文件: T6557752.java
public static void main(String[] args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    task.analyze();
    trees = Trees.instance(task);
    MyVisitor myVisitor = new MyVisitor();
    for (CompilationUnitTree ast : asts) {
        myVisitor.compilationUnit = ast;
        myVisitor.scan(ast, null);
    }

    if (!myVisitor.foundError) {
        throw new AssertionError("Expected error not found!");
    }
}
 
源代码8 项目: openjdk-jdk8u-backup   文件: T7086601b.java
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

        for (TypeKind a1 : TypeKind.values()) {
            for (TypeKind a2 : TypeKind.values()) {
                for (TypeKind a3 : TypeKind.values()) {
                    for (MethodCallKind mck : MethodCallKind.values()) {
                        new T7086601b(a1, a2, a3, mck).run(comp, fm);
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
源代码9 项目: TencentKona-8   文件: TestSuperclass.java
public static void main(String... args) throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
    int errors = 0;

    for (ClassKind ck: ClassKind.values()) {
        for (GenericKind gk: GenericKind.values()) {
            for (SuperKind sk: SuperKind.values()) {
                errors += new TestSuperclass(ck, gk, sk).run(comp, fm);
            }
        }
    }

    if (errors > 0)
        throw new Exception(errors + " errors found");
}
 
源代码10 项目: TencentKona-8   文件: TestSuperclass.java
int run(JavaCompiler comp, StandardJavaFileManager fm) throws IOException {
    System.err.println("test: ck:" + ck + " gk:" + gk + " sk:" + sk);
    File testDir = new File(ck + "-" + gk + "-" + sk);
    testDir.mkdirs();
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(testDir));

    JavaSource js = new JavaSource();
    System.err.println(js.getCharContent(false));
    CompilationTask t = comp.getTask(null, fm, null, null, null, Arrays.asList(js));
    if (!t.call())
        throw new Error("compilation failed");

    File testClass = new File(testDir, "Test.class");
    String out = javap(testClass);

    // Extract class sig from first line of Java source
    String expect = js.source.replaceAll("(?s)^(.* Test[^{]+?) *\\{.*", "$1");

    // Extract class sig from line from javap output
    String found = out.replaceAll("(?s).*\n(.* Test[^{]+?) *\\{.*", "$1");

    checkEqual("class signature", expect, found);

    return errors;
}
 
源代码11 项目: openjdk-jdk9   文件: InterruptedExceptionTest.java
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {

            for (XlintOption xlint : XlintOption.values()) {
                for (SuppressLevel suppress_decl : SuppressLevel.values()) {
                    for (SuppressLevel suppress_use : SuppressLevel.values()) {
                        for (ClassKind ck : ClassKind.values()) {
                            for (ExceptionKind ek_decl : ExceptionKind.values()) {
                                for (ExceptionKind ek_use : ExceptionKind.values()) {
                                    new InterruptedExceptionTest(xlint, suppress_decl,
                                            suppress_use, ck, ek_decl, ek_use).run(comp, fm);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 
源代码12 项目: openjdk-jdk8u   文件: InnerClassCannotBeVerified.java
void run() throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource();
    JavacTask ct = (JavacTask)comp.getTask(null, null, null,
            null, null, Arrays.asList(source));
    try {
        if (!ct.call()) {
            throw new AssertionError(errorMessage +
                    source.getCharContent(true));
        }
    } catch (Throwable ex) {
        throw new AssertionError(errorMessage +
                source.getCharContent(true));
    }
    check();
}
 
源代码13 项目: openjdk-jdk8u   文件: Abort.java
public static void main(String... args) throws Exception {

        String SCRATCH_DIR = System.getProperty("user.dir");
        JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
        java.io.File testDir = new java.io.File(SCRATCH_DIR);

        sourceA.dumpTo(testDir);
        sourceB.dumpTo(testDir);

        DiagnosticChecker diagChecker = new DiagnosticChecker();
        JavacTask ct = (JavacTask)javacTool.getTask(null, null, diagChecker,
                Arrays.asList("-XDrawDiagnostics", "-cp", testDir.getAbsolutePath()),
                null, Arrays.asList(sourceA.asJFO(testDir)));
        try {
            ct.analyze();
        } catch (Throwable ex) {
            //ignore abort exception thrown by javac
        }

        if (!diagChecker.errorFound) {
            throw new AssertionError("Missing diagnostic");
        }
    }
 
void run() throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    File classesDir = new File(System.getProperty("user.dir"), "classes");
    classesDir.mkdirs();
    JavaSource[] sources = new JavaSource[]{
        new JavaSource("TestOneIgnorableChar", "AA\\u0000BB"),
        new JavaSource("TestMultipleIgnorableChar", "AA\\u0000\\u0000\\u0000BB")};
    JavacTask ct = (JavacTask)comp.getTask(null, null, null,
            Arrays.asList("-d", classesDir.getPath()),
            null, Arrays.asList(sources));
    try {
        if (!ct.call()) {
            throw new AssertionError("Error thrown when compiling test cases");
        }
    } catch (Throwable ex) {
        throw new AssertionError("Error thrown when compiling test cases");
    }
    check(classesDir,
            "TestOneIgnorableChar.class",
            "TestOneIgnorableChar$AABB.class",
            "TestMultipleIgnorableChar.class",
            "TestMultipleIgnorableChar$AABB.class");
    if (errors > 0)
        throw new AssertionError("There are some errors in the test check the error output");
}
 
void run() throws Exception {
    Context context = new Context();
    JavacFileManager.preRegister(context);
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, Arrays.asList(new JavaSource()));
    Iterable<? extends CompilationUnitTree> elements = ct.parse();
    ct.analyze();
    Assert.check(elements.iterator().hasNext());
    JCTree topLevel = (JCTree)elements.iterator().next();
    new TreeScanner() {
        @Override
        public void visitReference(JCMemberReference tree) {
            Assert.check(tree.getOverloadKind() != null);
        }
    }.scan(topLevel);
}
 
源代码16 项目: netbeans   文件: MRJARCachingFileManagerTest.java
public void testJavac() throws Exception {
    final JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fm = jc.getStandardFileManager(
            null,
            Locale.ENGLISH,
            Charset.forName("UTF-8"));  //NOI18N
    fm.setLocation(
            StandardLocation.CLASS_PATH,
            Collections.singleton(FileUtil.archiveOrDirForURL(mvCp.entries().get(0).getURL())));
    Iterable<JavaFileObject> res = fm.list(
            StandardLocation.CLASS_PATH,
            "", //NOI18N
            EnumSet.of(JavaFileObject.Kind.CLASS),
            true);
    assertEquals(3, StreamSupport.stream(res.spliterator(), false).count());
}
 
源代码17 项目: openjdk-jdk9   文件: TestSuperclass.java
public static void main(String... args) throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        int errors = 0;

        for (ClassKind ck: ClassKind.values()) {
            for (GenericKind gk: GenericKind.values()) {
                for (SuperKind sk: SuperKind.values()) {
                    errors += new TestSuperclass(ck, gk, sk).run(comp, fm);
                }
            }
        }

        if (errors > 0)
            throw new Exception(errors + " errors found");
    }
}
 
源代码18 项目: openjdk-jdk8u-backup   文件: T6963934.java
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
            fileManager.getJavaFileObjects(thisSrc));
    CompilationUnitTree tree = task.parse().iterator().next();
    int count = 0;
    for (ImportTree importTree : tree.getImports()) {
        System.out.println(importTree);
        count++;
    }
    int expected = 7;
    if (count != expected)
        throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
 
源代码19 项目: openjdk-jdk8u   文件: TestBootNativeLibraryPath.java
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
void generateFilesNeeded() throws Exception {

        StringJavaFileObject[] CSource = new StringJavaFileObject[] {
            new StringJavaFileObject("C.java",
                "class C {C(String s) {}}"),
        };

        List<StringJavaFileObject> AandBSource = Arrays.asList(
                new StringJavaFileObject("A.java",
                    "class A {void test() {new B(null);new C(null);}}"),
                new StringJavaFileObject("B.java",
                    "class B {B(String s) {}}")
        );

        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
        JavacTask compileC = (JavacTask)tool.getTask(null, null, null, null, null,
                Arrays.asList(CSource));
        if (!compileC.call()) {
            throw new AssertionError("Compilation error while compiling C.java sources");
        }
        JavacTask compileAB = (JavacTask)tool.getTask(null, null, null,
                Arrays.asList("-cp", "."), null, AandBSource);
        if (!compileAB.call()) {
            throw new AssertionError("Compilation error while compiling A and B sources");
        }
    }
 
源代码21 项目: TencentKona-8   文件: Main.java
public static void main(String[] args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
    trees = Trees.instance(task);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    task.analyze();
    for (CompilationUnitTree ast : asts) {
        new MyVisitor().scan(ast, null);
    }
}
 
源代码22 项目: openjdk-jdk9   文件: InnerClassCannotBeVerified.java
void run() throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource();
    JavacTask ct = (JavacTask)comp.getTask(null, null, null,
            null, null, Arrays.asList(source));
    try {
        if (!ct.call()) {
            throw new AssertionError(errorMessage +
                    source.getCharContent(true));
        }
    } catch (Throwable ex) {
        throw new AssertionError(errorMessage +
                source.getCharContent(true));
    }
    check();
}
 
public static void main(String... args) throws Exception {

        //create default shared JavaCompiler - reused across multiple compilations
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);

        for (VersionKind vk : VersionKind.values()) {
            for (EnclosingKind ek : EnclosingKind.values()) {
                for (MethodKind mk : MethodKind.values()) {
                    for (ModifierKind modk1 : ModifierKind.values()) {
                        for (ModifierKind modk2 : ModifierKind.values()) {
                            new TestDefaultMethodsSyntax(vk, ek, mk, modk1, modk2).run(comp, fm);
                        }
                    }
                }
            }
        }
        System.out.println("Total check executed: " + checkCount);
    }
 
源代码24 项目: jdk8u60   文件: T7042566.java
@Override
public void run() {
    int id = checkCount.incrementAndGet();
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource(id);
    ErrorChecker ec = new ErrorChecker();
    JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), ec,
            null, null, Arrays.asList(source));
    ct.call();
    check(source, ec, id);
}
 
源代码25 项目: openjdk-jdk9   文件: T7142086.java
void run(List<JavaFileObject> sources) throws Exception {
    DiagnosticChecker dc = new DiagnosticChecker();
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        JavacTask ct = (JavacTask)comp.getTask(null, fm, dc,
                null, null, sources);
        ct.analyze();
    }
}
 
源代码26 项目: Bats   文件: JDKClassCompiler.java
public static JDKClassCompiler newInstance(ClassLoader classLoader, boolean debug) {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  if (compiler == null) {
    throw new RuntimeException("JDK Java compiler not available - probably you're running Drill with a JRE and not a JDK");
  }
  return new JDKClassCompiler(compiler, classLoader, debug);
}
 
源代码27 项目: Bats   文件: JDKClassCompiler.java
private JDKClassCompiler(JavaCompiler compiler, ClassLoader classLoader, boolean debug) {
  super(debug);
  this.compiler = compiler;
  this.listener = new DrillDiagnosticListener();
  this.fileManager = new DrillJavaFileManager(compiler.getStandardFileManager(listener, null, Charsets.UTF_8), classLoader);
  this.compilerOptions = Lists.newArrayList(this.debug ? "-g:source,lines,vars" : "-g:none");
}
 
源代码28 项目: openjdk-jdk9   文件: TestCircularClassfile.java
public static void main(String... args) throws Exception {
    JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        int count = 0;
        for (SourceKind sk1 : SourceKind.values()) {
            for (SourceKind sk2 : SourceKind.values()) {
                for (TestKind tk : TestKind.values()) {
                    for (ClientKind ck : ClientKind.values()) {
                        new TestCircularClassfile("sub_"+count++, sk1, sk2, tk, ck).check(comp, fm);
                    }
                }
            }
        }
    }
}
 
源代码29 项目: chaosblade-exec-jvm   文件: JavaCodeScriptEngine.java
private Class compileClass(ClassLoader classLoader, String className, String scriptId, String content) {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    if (javaCompiler == null) {
        throw new ScriptException("Not found system java compile");
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaFileObject javaFileObject = new InputStringJavaFileObject(className, content);
    StandardJavaFileManager standardFileManager = javaCompiler.getStandardFileManager(null, null, CHARSET_UTF8);
    InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(classLoader, standardFileManager);
    JavaCompiler.CompilationTask compilationTask = javaCompiler.getTask(null, fileManager, diagnostics, null, null,
        Arrays.asList(javaFileObject));
    if (Boolean.TRUE.equals(compilationTask.call())) {
        try {
            return new CompiledClassLoader(classLoader, fileManager.getOutputs()).loadClass(className);
        } catch (Exception ce) {
            throw convertToScriptException("compile class failed:" + className, scriptId, ce);
        }
    } else {
        StringBuilder reporter = new StringBuilder(1024);
        reporter.append("Compilation failed.\n");
        try {
            generateDiagnosticReport(diagnostics, reporter);
        } catch (IOException e) {
            reporter.append("io exception:" + e.getMessage());
        }
        throw new ScriptException(reporter.toString());
    }
}
 
源代码30 项目: TencentKona-8   文件: T7093325.java
@Override
public void run() {
    int id = checkCount.incrementAndGet();
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource(id);
    JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), null,
            null, null, Arrays.asList(source));
    ct.call();
    verifyBytecode(source, id);
}