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


Java ToolProvider.getSystemJavaCompiler方法代碼示例

本文整理匯總了Java中javax.tools.ToolProvider.getSystemJavaCompiler方法的典型用法代碼示例。如果您正苦於以下問題:Java ToolProvider.getSystemJavaCompiler方法的具體用法?Java ToolProvider.getSystemJavaCompiler怎麽用?Java ToolProvider.getSystemJavaCompiler使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.tools.ToolProvider的用法示例。


在下文中一共展示了ToolProvider.getSystemJavaCompiler方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: run

import javax.tools.ToolProvider; //導入方法依賴的package包/類
void run() throws IOException {
    String lineSep = System.getProperty("line.separator");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
         StringWriter out = new StringWriter();
         PrintWriter outWriter = new PrintWriter(out)) {
        Iterable<? extends JavaFileObject> input =
                fm.getJavaFileObjects(System.getProperty("test.src") + "/ReleaseOption.java");
        List<String> options = Arrays.asList("--release", "7", "-XDrawDiagnostics");

        compiler.getTask(outWriter, fm, null, options, null, input).call();
        String expected =
                "ReleaseOption.java:9:49: compiler.err.doesnt.exist: java.util.stream" + lineSep +
                "1 error" + lineSep;
        if (!expected.equals(out.toString())) {
            throw new AssertionError("Unexpected output: " + out.toString());
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:20,代碼來源:ReleaseOptionThroughAPI.java

示例2: javac

import javax.tools.ToolProvider; //導入方法依賴的package包/類
static void javac(Path dest, List<Path> sourceFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager =
                 compiler.getStandardFileManager(null, null, null)) {
        List<File> files = sourceFiles.stream()
                                      .map(p -> p.toFile())
                                      .collect(Collectors.toList());
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromFiles(files);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
                                Arrays.asList(dest.toFile()));
        fileManager.setLocation(StandardLocation.CLASS_PATH,
                                Arrays.asList(TEST_CLASSES.toFile()));
        JavaCompiler.CompilationTask task = compiler
                .getTask(null, fileManager, null, null, null, compilationUnits);
        boolean passed = task.call();
        if (!passed)
            throw new RuntimeException("Error compiling " + files);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:FailureAtomicity.java

示例3: loadBadClass

import javax.tools.ToolProvider; //導入方法依賴的package包/類
private static BadClassFile loadBadClass(String className) {
    // load the class, and save the thrown BadClassFile exception
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null,
            Arrays.asList("-classpath", classesdir.getPath()), null, null);
    Symtab syms = Symtab.instance(task.getContext());
    task.ensureEntered();
    BadClassFile badClassFile;
    try {
        com.sun.tools.javac.main.JavaCompiler.instance(task.getContext())
                .resolveIdent(syms.unnamedModule, className).complete();
    } catch (BadClassFile e) {
        return e;
    }
    return null;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:BadConstantValue.java

示例4: parse

import javax.tools.ToolProvider; //導入方法依賴的package包/類
static List<? extends Tree> parse(String srcfile) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(srcfile);
    String classPath = System.getProperty("java.class.path");
    List<String> options = Arrays.asList("-classpath", classPath);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    Context context = new Context();
    JavacTaskImpl task = (JavacTaskImpl) ((JavacTool) compiler).getTask(null, null,
            diagnostics, options, null, fileObjects, context);
    TrialParserFactory.instance(context);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Iterator<? extends CompilationUnitTree> it = asts.iterator();
    if (it.hasNext()) {
        CompilationUnitTree cut = it.next();
        return cut.getTypeDecls();
    } else {
        throw new AssertionError("Expected compilation unit");
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:JavacExtensionTest.java

示例5: testModuleSymbolOutterMostClass

import javax.tools.ToolProvider; //導入方法依賴的package包/類
@Test
public void testModuleSymbolOutterMostClass(Path base) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path moduleSrc = base.resolve("module-src");
        Path m1 = moduleSrc.resolve("m1x");

        tb.writeJavaFiles(m1, "module m1x { }");

        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(findJavaFiles(moduleSrc));
        com.sun.source.util.JavacTask task =
            (com.sun.source.util.JavacTask) compiler.getTask(null, fm, null, null, null, files);

        task.analyze();

        ModuleSymbol msym = (ModuleSymbol) task.getElements().getModuleElement("m1x");

        msym.outermostClass();
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:EdgeCases.java

示例6: setLocation

import javax.tools.ToolProvider; //導入方法依賴的package包/類
@Test
public void setLocation(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src.resolve("m1x"), "module m1x { }", "package a; class A { }");
    Path modules = base.resolve("modules");
    tb.createDirectories(modules);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
        fm.setLocationFromPaths(StandardLocation.MODULE_SOURCE_PATH, List.of(src));
        new JavacTask(tb)
                .options("-XDrawDiagnostics")
                .fileManager(fm)
                .outdir(modules)
                .files(findJavaFiles(src))
                .run()
                .writeAll();

        checkFiles(modules.resolve("m1x/module-info.class"), modules.resolve("m1x/a/A.class"));
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:22,代碼來源:ModuleSourcePathTest.java

示例7: main

import javax.tools.ToolProvider; //導入方法依賴的package包/類
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 (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);
        }
    }
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:TestSelfRef.java

示例8: compile

import javax.tools.ToolProvider; //導入方法依賴的package包/類
static void compile(JavaSource src) throws IOException {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(ba);
    File tempDir = new File(".");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector dc = new DiagnosticCollector();
    try (JavaFileManager javaFileManager = getJavaFileManager(compiler, dc)) {
        List<String> options = new ArrayList<>();
        options.add("-cp");
        options.add(tempDir.getPath());
        options.add("-d");
        options.add(tempDir.getPath());
        options.add("--should-stop:at=GENERATE");

        List<JavaFileObject> sources = new ArrayList<>();
        sources.add(src);
        JavaCompiler.CompilationTask task =
                compiler.getTask(writer, javaFileManager,
                dc, options, null,
                sources);
        task.call();
        for (Diagnostic diagnostic : (List<Diagnostic>) dc.getDiagnostics()) {
            long actualStart = diagnostic.getStartPosition();
            long actualEnd = diagnostic.getEndPosition();
            System.out.println("Source: " + src.source);
            System.out.println("Diagnostic: " + diagnostic);
            System.out.print("Start position: Expected: " + src.startPos);
            System.out.println(", Actual: " + actualStart);
            System.out.print("End position: Expected: " + src.endPos);
            System.out.println(", Actual: " + actualEnd);
            if (src.startPos != actualStart || src.endPos != actualEnd) {
                throw new RuntimeException("error: trees don't match");
            }
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:37,代碼來源:TreeEndPosTest.java

示例9: main

import javax.tools.ToolProvider; //導入方法依賴的package包/類
public static void main(String... args) throws IOException {
    if (args.length != 1) {
        System.err.println("Not enough arguments.");
        System.err.println("Usage:");
        System.err.println("    java " + Probe.class.getName() + " <output-file>");
        return ;
    }

    File outFile = new File(args[0]);
    Charset cs = Charset.forName("UTF-8");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    OutputStream out = new FileOutputStream(outFile);

    try {
        Iterable<JavaFileObject> bcpFiles =
                fm.list(StandardLocation.PLATFORM_CLASS_PATH, "", EnumSet.of(Kind.CLASS), true);

        for (JavaFileObject jfo : bcpFiles) {
            InputStream in = new BufferedInputStream(jfo.openInputStream());
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                StringBuilder textual = new StringBuilder();
                int read;

                while ((read = in.read()) != (-1)) {
                    baos.write(read);
                    textual.append(String.format("%02x", read));
                }

                textual.append("\n");
                out.write(textual.toString().getBytes(cs));
            } finally {
                in.close();
            }
        }
    } finally {
        out.close();
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:41,代碼來源:Probe.java

示例10: compileAndCheck

import javax.tools.ToolProvider; //導入方法依賴的package包/類
void compileAndCheck() throws Exception {
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource();
    JavacTask ct = (JavacTask)tool.getTask(null, fm, null,
            null, null, Arrays.asList(source));
    ct.call();
    verifyBytecode(source);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:9,代碼來源:T7003595.java

示例11: testThroughFormatterFormat

import javax.tools.ToolProvider; //導入方法依賴的package包/類
public void testThroughFormatterFormat() throws IOException {
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    DiagnosticChecker dc = new DiagnosticChecker("compiler.err.prob.found.req");
    JavacTask ct = (JavacTask)tool.getTask(null, null, dc, null, null, Arrays.asList(new JavaSource()));
    ct.analyze();
    DiagnosticFormatter<JCDiagnostic> formatter =
            Log.instance(((JavacTaskImpl) ct).getContext()).getDiagnosticFormatter();
    String msg = formatter.formatMessage(dc.diag, Locale.getDefault());
    //no redundant package qualifiers
    Assert.check(msg.indexOf("java.") == -1, msg);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:12,代碼來源:T7116676.java

示例12: main

import javax.tools.ToolProvider; //導入方法依賴的package包/類
public static void main(String... args) {
    javax.tools.JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, null, null, null, null, null);
    Symtab syms = Symtab.instance(task.getContext());
    task.ensureEntered();
    JavaCompiler compiler = JavaCompiler.instance(task.getContext());
    try {
        compiler.resolveIdent(syms.unnamedModule, "Test$1").complete();
    } catch (CompletionFailure ex) {
        System.err.println("Got expected completion failure: " + ex.getLocalizedMessage());
        return;
    }
    throw new AssertionError("No error reported");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:15,代碼來源:T6400303.java

示例13: run

import javax.tools.ToolProvider; //導入方法依賴的package包/類
public boolean run() throws Util.Exit {

        Util util = new Util(log, diagnosticListener);

        if (noArgs || help) {
            showHelp();
            return help; // treat noArgs as an error for purposes of exit code
        }

        if (version || fullVersion) {
            showVersion(fullVersion);
            return true;
        }

        util.verbose = verbose;

        Gen g;

        if (llni)
            g = new LLNI(doubleAlign, util);
        else {
//            if (stubs)
//                throw new BadArgs("jni.no.stubs");
            g = new JNI(util);
        }

        if (ofile != null) {
            if (!(fileManager instanceof StandardJavaFileManager)) {
                diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-o"));
                return false;
            }
            Iterable<? extends JavaFileObject> iter =
                    ((StandardJavaFileManager) fileManager).getJavaFileObjectsFromFiles(Collections.singleton(ofile));
            JavaFileObject fo = iter.iterator().next();
            g.setOutFile(fo);
        } else {
            if (odir != null) {
                if (!(fileManager instanceof StandardJavaFileManager)) {
                    diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-d"));
                    return false;
                }

                if (!odir.exists())
                    if (!odir.mkdirs())
                        util.error("cant.create.dir", odir.toString());
                try {
                    ((StandardJavaFileManager) fileManager).setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(odir));
                } catch (IOException e) {
                    Object msg = e.getLocalizedMessage();
                    if (msg == null) {
                        msg = e;
                    }
                    diagnosticListener.report(createDiagnostic("err.ioerror", odir, msg));
                    return false;
                }
            }
            g.setFileManager(fileManager);
        }

        /*
         * Force set to false will turn off smarts about checking file
         * content before writing.
         */
        g.setForce(force);

        if (fileManager instanceof JavahFileManager)
            ((JavahFileManager) fileManager).setSymbolFileEnabled(false);

        JavaCompiler c = ToolProvider.getSystemJavaCompiler();
        List<String> opts = new ArrayList<String>();
        opts.add("-proc:only");
        opts.addAll(javac_extras);
        CompilationTask t = c.getTask(log, fileManager, diagnosticListener, opts, classes, null);
        JavahProcessor p = new JavahProcessor(g);
        t.setProcessors(Collections.singleton(p));

        boolean ok = t.call();
        if (p.exit != null)
            throw new Util.Exit(p.exit);
        return ok;
    }
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:82,代碼來源:JavahTask.java

示例14: compile

import javax.tools.ToolProvider; //導入方法依賴的package包/類
/**
 * Compiles sources with -XDrawDiagnostics flag and
 * returns the output of compilation.
 *
 * @param sources sources
 * @return the result of compilation
 */
private String compile(ToolBox.JavaSource...sources) {
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    StringWriter writer = new StringWriter();
    JavaCompiler.CompilationTask ct = jc.getTask(writer, null, null,
            Arrays.asList("-XDrawDiagnostics"),
            null, Arrays.asList(sources));
    if (ct.call()) {
        throw new RuntimeException("Expected compilation failure.");
    }
    return writer.toString().replace(ToolBox.lineSeparator, "\n");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:NegativeCyclicDependencyTest.java

示例15: testUnnamed

import javax.tools.ToolProvider; //導入方法依賴的package包/類
@Test
public void testUnnamed(Path base) throws Exception {
    Path moduleSrc = base.resolve("module-src");
    Path m1 = moduleSrc.resolve("m1x");

    tb.writeJavaFiles(m1,
                      "module m1x { exports m1x; }",
                      "package m1x; public class M1 {}");

    Path m2 = moduleSrc.resolve("m2x");

    tb.writeJavaFiles(m2,
                      "module m2x { exports m2x; }",
                      "package m2x; public class M2 {}");

    Path modulePath = base.resolve("module-path");

    Files.createDirectories(modulePath);

    new JavacTask(tb)
            .options("--module-source-path", moduleSrc.toString())
            .outdir(modulePath)
            .files(findJavaFiles(moduleSrc))
            .run()
            .writeAll();

    Path cpSrc = base.resolve("cp-src");

    tb.writeJavaFiles(cpSrc,
                      "package cp; public class CP {}");

    Path cp = base.resolve("cp");

    Files.createDirectories(cp);

    new JavacTask(tb)
            .outdir(cp)
            .files(findJavaFiles(cpSrc))
            .run()
            .writeAll();

    Path src = base.resolve("src");

    tb.writeJavaFiles(src,
                      "package test; public class Test1 {}",
                      "package test; public class Test2 {}");

    Path out = base.resolve("out");

    Files.createDirectories(out);

    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
        com.sun.source.util.JavacTask task =
            (com.sun.source.util.JavacTask) javaCompiler.getTask(null,
                                                          null,
                                                          d -> { throw new IllegalStateException(d.toString()); },
                                                          Arrays.asList("--module-path", modulePath.toString(),
                                                                        "--class-path", cp.toString(),
                                                                        "-sourcepath", src.toString()),
                                                          null,
                                                          fm.getJavaFileObjects(src.resolve("test").resolve("Test2.java")));
        assertNotNull(task.getElements().getTypeElement("java.lang.String"));
        assertNotNull(task.getElements().getTypeElement("javax.tools.ToolProvider"));
        assertNull(task.getElements().getTypeElement("m1x.M1"));
        assertNull(task.getElements().getTypeElement("m2x.M2"));
        assertNotNull(task.getElements().getTypeElement("cp.CP"));
        assertNotNull(task.getElements().getTypeElement("test.Test1"));
        assertNotNull(task.getElements().getTypeElement("test.Test2"));
        assertNotNull(task.getElements().getModuleElement("java.base"));
        assertNotNull(task.getElements().getModuleElement("java.compiler"));
        assertNull(task.getElements().getModuleElement("m1x"));
        assertNull(task.getElements().getModuleElement("m2x"));
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:76,代碼來源:QueryBeforeEnter.java


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