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


Java JavaCompiler類代碼示例

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


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

示例1: run

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

import javax.tools.JavaCompiler; //導入依賴的package包/類
/**
 * Compile the provided class. The className may have a package separated by /. For example:
 * my/package/myclass
 * 
 * @param className Name of the class to compile.
 * @param classCode Plain text contents of the class
 * @return The byte contents of the compiled class.
 * @throws IOException
 */
public byte[] compileClass(final String className, final String classCode) throws IOException {
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  OutputStreamJavaFileManager<JavaFileManager> fileManager =
      new OutputStreamJavaFileManager<JavaFileManager>(
          javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);

  List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
  fileObjects.add(new JavaSourceFromString(className, classCode));

  List<String> options = Arrays.asList("-classpath", this.classPath);
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
    StringBuilder errorMsg = new StringBuilder();
    for (Diagnostic d : diagnostics.getDiagnostics()) {
      String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(),
          d.getMessage(null));
      errorMsg.append(err);
      System.err.print(err);
    }
    throw new IOException(errorMsg.toString());
  }
  return byteArrayOutputStream.toByteArray();
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:35,代碼來源:ClassBuilder.java

示例3: testJavac

import javax.tools.JavaCompiler; //導入依賴的package包/類
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());
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:17,代碼來源:MRJARCachingFileManagerTest.java

示例4: compile

import javax.tools.JavaCompiler; //導入依賴的package包/類
private void compile(String option, Path destDir, Path... files)
        throws IOException
{
    System.err.println("compile...");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Iterable<? extends JavaFileObject> fileObjects =
            fm.getJavaFileObjectsFromPaths(Arrays.asList(files));

        List<String> options = new ArrayList<>();
        if (option != null) {
            options.add(option);
        }
        if (destDir != null) {
            options.add("-d");
            options.add(destDir.toString());
        }
        options.add("-cp");
        options.add(System.getProperty("test.classes", "."));

        JavaCompiler.CompilationTask task =
            compiler.getTask(null, fm, null, options, null, fileObjects);
        if (!task.call())
            throw new AssertionError("compilation failed");
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:27,代碼來源:PackageInfoTest.java

示例5: testTreePathForModuleDeclWithImport

import javax.tools.JavaCompiler; //導入依賴的package包/類
@Test
public void testTreePathForModuleDeclWithImport(Path base) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path src = base.resolve("src");
        tb.writeJavaFiles(src, "import java.lang.Deprecated; /** Test module */ @Deprecated 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);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:25,代碼來源:ModuleInfoTreeAccess.java

示例6: parameters

import javax.tools.JavaCompiler; //導入依賴的package包/類
@Parameters(name="{0}")
public static Collection<Object[]> parameters() {
  JavaCompiler systemJavaCompiler = Compiler.systemJavaCompiler();
  JavaCompiler eclipseCompiler = Compiler.eclipseCompiler();
  return Arrays.asList(new Object[][] {
    {
      "includeAccessorsWithSystemJavaCompiler",
      systemJavaCompiler,
      config("includeDynamicAccessors", true, "includeDynamicGetters", true, "includeDynamicSetters", true, "includeDynamicBuilders", true),
      "/schema/dynamic/parentType.json",
      Matchers.empty()
    },
    {
      "includeAccessorsWithEclipseCompiler",
      eclipseCompiler,
      config("includeDynamicAccessors", true, "includeDynamicGetters", true, "includeDynamicSetters", true, "includeDynamicBuilders", true),
      "/schema/dynamic/parentType.json",
      onlyCastExceptions()
    }
  });
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:22,代碼來源:CompilerWarningIT.java

示例7: main

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

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

示例9: javac

import javax.tools.JavaCompiler; //導入依賴的package包/類
static void javac(Path dest, Path... sourceFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager =
                compiler.getStandardFileManager(null, null, null)) {

        List<File> files = Stream.of(sourceFiles)
                .map(p -> p.toFile())
                .collect(Collectors.toList());
        List<File> dests = Stream.of(dest)
                .map(p -> p.toFile())
                .collect(Collectors.toList());
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromFiles(files);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, dests);
        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,代碼行數:22,代碼來源:Basic.java

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

示例11: loadBadClass

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

示例12: compileTestClass

import javax.tools.JavaCompiler; //導入依賴的package包/類
/**
 * Compiles the test class with bogus code into a .class file.
 * Unfortunately it's very tedious.
 * @param counter Unique test counter.
 * @param packageNameSuffix Package name suffix (e.g. ".suffix") for nesting, or "".
 * @return The resulting .class file and the location in jar it is supposed to go to.
 */
private static FileAndPath compileTestClass(long counter,
    String packageNameSuffix, String classNamePrefix) throws Exception {
  classNamePrefix = classNamePrefix + counter;
  String packageName = makePackageName(packageNameSuffix, counter);
  String javaPath = basePath + classNamePrefix + ".java";
  String classPath = basePath + classNamePrefix + ".class";
  PrintStream source = new PrintStream(javaPath);
  source.println("package " + packageName + ";");
  source.println("public class " + classNamePrefix
      + " { public static void main(String[] args) { } };");
  source.close();
  JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
  int result = jc.run(null, null, null, javaPath);
  assertEquals(0, result);
  File classFile = new File(classPath);
  assertTrue(classFile.exists());
  return new FileAndPath(packageName.replace('.', '/') + '/', classFile);
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:26,代碼來源:TestClassFinder.java

示例13: run

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

示例14: compileJavaFiles

import javax.tools.JavaCompiler; //導入依賴的package包/類
/**
 * 動態編譯java文件
 * @param files
 */
private void compileJavaFiles(List<File> files) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    //獲取java文件管理類
    StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
    //獲取java文件對象迭代器
    Iterable<? extends JavaFileObject> it = manager.getJavaFileObjectsFromFiles(files);
    //設置編譯參數
    ArrayList<String> ops = new ArrayList<>();
    ops.add("-Xlint:unchecked");
    //獲取編譯任務
    JavaCompiler.CompilationTask task = compiler.getTask(null, manager, null, ops, null, it);
    //執行編譯任務
    task.call();
}
 
開發者ID:itfsw,項目名稱:mybatis-generator-plugin,代碼行數:20,代碼來源:MyBatisGeneratorTool.java

示例15: main

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


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