当前位置: 首页>>代码示例>>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;未经允许,请勿转载。