当前位置: 首页>>代码示例>>Java>>正文


Java JavaCompiler.getTask方法代码示例

本文整理汇总了Java中javax.tools.JavaCompiler.getTask方法的典型用法代码示例。如果您正苦于以下问题:Java JavaCompiler.getTask方法的具体用法?Java JavaCompiler.getTask怎么用?Java JavaCompiler.getTask使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.tools.JavaCompiler的用法示例。


在下文中一共展示了JavaCompiler.getTask方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: run

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public void run() throws IOException {
    File srcDir = new File(System.getProperty("test.src"));
    File thisFile = new File(srcDir, getClass().getName() + ".java");

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {

        List<String> opts = Arrays.asList("-proc:only", "-doe");
        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile);
        JavacTask t = (JavacTask) c.getTask(null, fm, null, opts, null, files);
        t.setProcessors(Collections.singleton(this));
        boolean ok = t.call();
        if (!ok)
            throw new Error("compilation failed");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:TestGetScope.java

示例2: run

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public void run(JavaCompiler comp) {
    JavaSource source = new JavaSource();
    JavacTaskImpl ct = (JavacTaskImpl)comp.getTask(null, null, dc,
            Arrays.asList("-g"), null, Arrays.asList(source));
    Context context = ct.getContext();
    Symtab syms = Symtab.instance(context);
    Names names = Names.instance(context);
    Types types = Types.instance(context);
    ct.addTaskListener(new Indifier(syms, names, types));
    try {
        ct.generate();
    } catch (Throwable t) {
        t.printStackTrace();
        throw new AssertionError(
                String.format("Error thrown when compiling following code\n%s",
                        source.source));
    }
    if (dc.diagFound) {
        throw new AssertionError(
                String.format("Diags found when compiling following code\n%s\n\n%s",
                        source.source, dc.printDiags()));
    }
    verifyBytecode();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:TestBootstrapMethodsCount.java

示例3: main

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
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);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:T6852595.java

示例4: main

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
    File src = new File("C.java");
    Writer w = new FileWriter(src);
    try {
        w.write("import static p.Generated.m;\nclass C { {m(); } }\n");
        w.flush();
    } finally {
        w.close();
    }
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null)) {
        JavaCompiler.CompilationTask task = jc.getTask(null, fm, null, null, null,
                                                       fm.getJavaFileObjects(src));
        task.setProcessors(Collections.singleton(new Proc()));
        if (!task.call()) {
            throw new Error("Test failed");
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:T7159016.java

示例5: compileDependencyClass

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
@BeforeClass
public static void compileDependencyClass() throws IOException, ClassNotFoundException {
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  Assume.assumeNotNull(javaCompiler);

  classes = temporaryFolder.newFolder("classes");;

  StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ROOT, UTF_8);
  fileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes));

  SimpleJavaFileObject compilationUnit = new SimpleJavaFileObject(URI.create("FooTest.java"), Kind.SOURCE) {
    String fooTestSource = Resources.toString(Resources.getResource("com/dremio/exec/compile/FooTest.java"), UTF_8);
    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
      return fooTestSource;
    }
  };

  CompilationTask task = javaCompiler.getTask(null, fileManager, null, Collections.<String>emptyList(), null, ImmutableList.of(compilationUnit));
  assertTrue(task.call());
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:22,代码来源:TestClassCompilers.java

示例6: compile

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException {
    JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null)) {
        if (classpaths.size() > 0)
            fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
        JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
        if (generate) {
            File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
            // @@@ Assert that this directory didn't exist, or start counter at max+1
            destDir.mkdirs();
            fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
            ct.generate();
            return destDir;
        }
        else {
            ct.analyze();
            return nullDir;
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:JavacTemplateTestBase.java

示例7: run

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    checkCount++;
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            null, null, Arrays.asList(source));
    ct.parse();
    if (diagChecker.errorFound) {
        throw new Error("Unexpected parser error for source:\n" +
            source.getCharContent(true));
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:11,代码来源:IntersectionTypeParserTest.java

示例8: compileAndCheck

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
void compileAndCheck(VarargsMethod m1, VarargsMethod m2, TypeKind actual, ArgumentsArity argsArity) throws Exception {
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavaSource source = new JavaSource(m1, m2, actual, argsArity);
    ErrorChecker ec = new ErrorChecker();
    JavacTask ct = (JavacTask)tool.getTask(null, fm, ec,
            null, null, Arrays.asList(source));
    ct.generate();
    check(source, ec, m1, m2, actual, argsArity);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:10,代码来源:T6199075.java

示例9: main

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2
            //      0123456789012345678901234
            return "class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null,
                                              compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    Tree tree = ((ClassTree)toplevel.getTypeDecls().get(0)).getMembers().get(0);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree);
    if (pos != 13)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree, pos));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:30,代码来源:T6402077.java

示例10: main

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static void main(String[] args) throws IOException {
    List<? extends JavaFileObject> files = Arrays.asList(new SourceFile());
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Context ctx = new Context();
    JavacFileManager.preRegister(ctx);
    checkImplementationCache(ct.analyze(), Types.instance(ctx));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:9,代码来源:ImplementationCacheTest.java

示例11: run

import javax.tools.JavaCompiler; //导入方法依赖的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

示例12: main

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
    write(test_java, test);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager manager =
            compiler.getStandardFileManager(null, null, null)) {
        Iterable<? extends JavaFileObject> units = manager.getJavaFileObjects(test_java);
        final StringWriter sw = new StringWriter();
        JavacTask task = (JavacTask) compiler.getTask(sw, manager, null, null,
                null, units);

        new TreeScanner<Boolean, Void>() {
            @Override
            public Boolean visitClass(ClassTree arg0, Void arg1) {
                sw.write(arg0.toString());
                return super.visitClass(arg0, arg1);
            }
        }.scan(task.parse(), null);

        System.out.println("output:");
        System.out.println(sw.toString());
        String found = sw.toString().replaceAll("\\s+", " ").trim();
        String expect = test.replaceAll("\\s+", " ").trim();
        if (!expect.equals(found)) {
            System.out.println("expect: " + expect);
            System.out.println("found:  " + found);
            throw new Exception("unexpected output");
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:31,代码来源:T6665791.java

示例13: test

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
private static void test(String classname, String expected) throws Exception {
    File classfile = new File(System.getProperty("test.classes", "."), classname + ".class");
    ClassFile cf = ClassFile.read(classfile);

    cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion,
             Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags,
            cf.this_class, cf.super_class, cf.interfaces, cf.fields,
            cf.methods, cf.attributes);

    new ClassWriter().write(cf, classfile);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null);
    Symtab syms = Symtab.instance(task.getContext());

    task.ensureEntered();

    try {
        Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(syms.unnamedModule, classname);

        clazz.complete();
    } catch (BadClassFile f) {
        JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1];
        assertEquals(expected, embeddedDiag.getCode());
        assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]);
        assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:29,代码来源:BadClassfile.java

示例14: run

import javax.tools.JavaCompiler; //导入方法依赖的package包/类
void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
    JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
            null, null, Arrays.asList(source));
    try {
        ct.analyze();
    } catch (Throwable ex) {
        fail("Error thrown when analyzing the following source:\n" + source.getCharContent(true));
    }
    check();
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:11,代码来源:FDTest.java

示例15: compile

import javax.tools.JavaCompiler; //导入方法依赖的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


注:本文中的javax.tools.JavaCompiler.getTask方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。