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


Java CompilationTask類代碼示例

本文整理匯總了Java中javax.tools.JavaCompiler.CompilationTask的典型用法代碼示例。如果您正苦於以下問題:Java CompilationTask類的具體用法?Java CompilationTask怎麽用?Java CompilationTask使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


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

示例1: parse

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
public static void parse(Path moduleInfoPath, ModuleClassVisitor moduleClassVisitor) throws IOException {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  try(StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(moduleInfoPath);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    JavacTask javacTask = (JavacTask)task;
    Iterable<? extends CompilationUnitTree> units= javacTask.parse();
    CompilationUnitTree unit = units.iterator().next();

    ModuleHandler moduleHandler = new ModuleHandler(moduleClassVisitor);
    TreeVisitor<?,?> visitor = (TreeVisitor<?,?>)Proxy.newProxyInstance(TreeVisitor.class.getClassLoader(), new Class<?>[]{ TreeVisitor.class},
        (proxy, method, args) -> {
          ModuleHandler.METHOD_MAP
          .getOrDefault(method.getName(), (handler, node, v) -> { 
            throw new AssertionError("invalid node " + node.getClass());
          })
          .visit(moduleHandler, (Tree)args[0], (TreeVisitor<?,?>)proxy);
          return null;
        });

    unit.accept(visitor, null);
  }
}
 
開發者ID:forax,項目名稱:moduletools,代碼行數:24,代碼來源:JavacModuleParser.java

示例2: run

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
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;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:26,代碼來源:TestSuperclass.java

示例3: main

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        List<File> files = new ArrayList<File>();
        files.add(new File(T6956462.class.getResource("TestClass.java").toURI()));
        final CompilationTask task = compiler.getTask(null, fm, null,
            null, null, fm.getJavaFileObjectsFromFiles(files));
        JavacTask javacTask = (JavacTask) task;
        for (CompilationUnitTree cu : javacTask.parse()) {
            cu.accept(new MyVisitor(javacTask), null);
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:T6956462.java

示例4: main

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
public static void main(String[] args) throws IOException {
    // Get a compiler tool
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    String srcdir = System.getProperty("test.src");
    File source = new File(srcdir, "T6378728.java");
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {

        CompilationTask task =
            compiler.getTask(null,
                             new ExceptionalFileManager(fm),
                             null,
                             Arrays.asList("-proc:only"),
                             null,
                             fm.getJavaFileObjectsFromFiles(Arrays.asList(source)));
        if (!task.call())
            throw new RuntimeException("Unexpected compilation failure");
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:T6378728.java

示例5: testSingleSourceDir

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
private void testSingleSourceDir(JavaCompiler javac) throws Exception {
    System.err.println("testSingleSourceDir");
    File tmpdir = new File("testSingleSourceDir");
    File srcdir = new File(tmpdir, "src");
    File destdir = new File(tmpdir, "dest");
    write(srcdir, "pkg/X.java", "package pkg; class X {}");
    write(srcdir, "resources/file.txt", "hello");
    destdir.mkdirs();

    CompilationTask task = javac.getTask(null, null, null,
            Arrays.asList("-sourcepath", srcdir.toString(), "-d", destdir.toString()),
            Collections.singleton("pkg.X"), null);
    task.setProcessors(Collections.singleton(new AnnoProc()));
    boolean result = task.call();
    System.err.println("javac result with single source dir: " + result);
    expect(result, true);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:18,代碼來源:TestGetResource2.java

示例6: testCompositeSourcePath

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
private void testCompositeSourcePath(JavaCompiler javac) throws Exception {
    System.err.println("testCompositeSearchPath");
    File tmpdir = new File("testCompositeSourcePath");
    File srcdir = new File(tmpdir, "src");
    File rsrcdir = new File(tmpdir, "rsrc");
    File destdir = new File(tmpdir, "dest");
    write(srcdir, "pkg/X.java", "package pkg; class X {}");
    write(rsrcdir, "resources/file.txt", "hello");
    destdir.mkdirs();

    CompilationTask task = javac.getTask(null, null, null,
            Arrays.asList("-sourcepath", srcdir + File.pathSeparator + rsrcdir, "-d", destdir.toString()),
            Collections.singleton("pkg.X"), null);
    task.setProcessors(Collections.singleton(new AnnoProc()));
    boolean result = task.call();
    System.err.println("javac result with composite source path: " + result);
    expect(result, true);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:TestGetResource2.java

示例7: testMissingResource

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
private void testMissingResource(JavaCompiler javac) throws Exception {
    System.err.println("testMissingResource");
    File tmpdir = new File("testMissingResource");
    File srcdir = new File(tmpdir, "src");
    File destdir = new File(tmpdir, "dest");
    write(srcdir, "pkg/X.java", "package pkg; class X {}");
    destdir.mkdirs();

    CompilationTask task = javac.getTask(null, null, null,
            Arrays.asList("-sourcepath", srcdir.toString(), "-d", destdir.toString()),
            Collections.singleton("pkg.X"), null);
    task.setProcessors(Collections.singleton(new AnnoProc()));
    boolean result = task.call();
    System.err.println("javac result when missing resource: " + result);
    expect(result, false);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:20,代碼來源:TestGetResource2.java

示例8: main

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
public static void main(String... args) throws Exception {
    String testSrc = System.getProperty("test.src");
    String testClasses = System.getProperty("test.classes");
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
        String thisName = TreePosRoundsTest.class.getName();
        File thisFile = new File(testSrc, thisName + ".java");
        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile);
        List<String> options = Arrays.asList(
                "-proc:only",
                "-processor", thisName,
                "-processorpath", testClasses);
        CompilationTask t = c.getTask(null, fm, null, options, null, files);
        boolean ok = t.call();
        if (!ok)
            throw new Exception("processing failed");
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:TreePosRoundsTest.java

示例9: createFile

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
File createFile(Dir dir) throws IOException {
    File src = new File(dir.file, classId + ".java");
    try (FileWriter w = new FileWriter(src)) {
        w.append("public class " + classId + " {}");
    }
    // If we're after the ".java" representation, we're done...
    if(dir == Dir.SOURCE_PATH)
        return src;
    // ...otherwise compile into a ".class".
    CompilationTask task = comp.getTask(null, fm, null, null, null,
            fm.getJavaFileObjects(src));
    File dest = new File(dir.file, classId + ".class");
    if(!task.call() || !dest.exists())
        throw new RuntimeException("Compilation failure.");
    src.delete();
    return dest;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:18,代碼來源:XPreferTest.java

示例10: callTask

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
void callTask(List<String> options, List<JavaFileObject> files) {
    out.print("compile: ");
    if (options != null) {
        for (String o: options) {
            if (o.length() > 64) {
                o = o.substring(0, 32) + "..." + o.substring(o.length() - 32);
            }
            out.print(" " + o);
        }
    }
    for (JavaFileObject f: files)
        out.print(" " + f.getName());
    out.println();
    CompilationTask t = compiler.getTask(out, fileManager, null, options, null, files);
    boolean ok = t.call();
    if (!ok)
        error("compilation failed");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:TestSearchPaths.java

示例11: test

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
void test(List<String> options, String expect) throws Exception {
    System.err.println("test: " + options);
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileObject f = new MyFileObject("myfo://test", "class Bad { Missing x; }");
    List<? extends JavaFileObject> files = Arrays.asList(f);
    CompilationTask task = javac.getTask(pw, null, null, options, null, files);
    boolean ok = task.call();
    pw.close();
    String out = sw.toString();
    if (!out.isEmpty())
        System.err.println(out);
    if (ok)
        throw new Exception("Compilation succeeded unexpectedly");
    if (!out.contains(expect))
        throw new Exception("expected text not found: " + expect);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:Test.java

示例12: run

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
void run() throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    System.err.println("using " + compiler.getClass()
            + " from " + compiler.getClass().getProtectionDomain().getCodeSource());

    CompilationTask task = compiler.getTask(null, null, null,
            Collections.singleton("-proc:only"),
            Collections.singleton("java.lang.Object"),
            null);
    task.setProcessors(Collections.singleton(new Proc()));
    check("compilation", task.call());

    task = compiler.getTask(null, null, null,
            Arrays.asList("-proc:only", "-AexpectFile"),
            Collections.singleton("java.lang.Object"),
            null);
    task.setProcessors(Collections.singleton(new Proc()));
    check("compilation", task.call());
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:20,代碼來源:T7068437.java

示例13: compileFiles

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
public static void compileFiles(File projectRoot, List<String> javaFiles) {
    DiagnosticCollector diagnosticCollector = new DiagnosticCollector();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.ENGLISH, Charset.forName("utf-8"));
    Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(javaFiles.toArray(new String[0]));
    File outputFolder = new File(projectRoot, "bin");
    if (!outputFolder.exists()) {
        outputFolder.mkdir();
    }
    String[] options = new String[] { "-d", outputFolder.getAbsolutePath() , "-g", "-proc:none"};
    final StringWriter output = new StringWriter();
    CompilationTask task = compiler.getTask(output, fileManager, diagnosticCollector, Arrays.asList(options), null, javaFileObjects);
    boolean result = task.call();
    if (!result) {
        throw new IllegalArgumentException(
            "Compilation failed:\n" + output);
    }
    List list = diagnosticCollector.getDiagnostics();
    for (Object object : list) {
        Diagnostic d = (Diagnostic) object;
        System.out.println(d.getMessage(Locale.ENGLISH));
    }
}
 
開發者ID:Microsoft,項目名稱:java-debug,代碼行數:23,代碼來源:CompileUtils.java

示例14: compileDependencyClass

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的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

示例15: compile

import javax.tools.JavaCompiler.CompilationTask; //導入依賴的package包/類
public static Class<?> compile(String mainClass, Code... codes) throws Exception {
	JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
	DynamicClassLoader cl = new DynamicClassLoader(ClassLoader.getSystemClassLoader());

	ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(null, null, null),
			null, cl);

	JavaFileObject[] sCodes = new JavaFileObject[codes.length];
	// List<CompiledCode> cCodes = new ArrayList<>();
	for (int i = 0; i < codes.length; i++) {
		SourceCode sourceCode = new SourceCode(codes[i].getClassName(), codes[i].getSourceCode());
		CompiledCode compiledCode = new CompiledCode(codes[i].getClassName());
		sCodes[i] = sourceCode;
		fileManager.addCode(compiledCode);
	}

	Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(sCodes);

	CompilationTask task = javac.getTask(null, fileManager, null, null, null, compilationUnits);
	task.call();
	return cl.loadClass(mainClass);
}
 
開發者ID:callakrsos,項目名稱:Gargoyle,代碼行數:23,代碼來源:InMemoryJavaCompiler.java


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