java在運行時動態編譯.java文件,轉載Stack OverFlow

原始地址:https://stackoverflow.com/questions/27608408/compiling-a-class-at-runtime-with-classpath

I’m currently trying to compile a class at runtime but for some reason it’s only working on one system. Both systems use the exact same code and have the same java version installed, but on one system my .java file compiles to a .class and on the other system I’m getting exceptions because some classes which are, or should be, in the classpath can’t be found.

The code I use to compile it is this:

private static File compile(File file) {
    try {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        List<String> optionList = new ArrayList<>();
        File jar = getJar(RuntimeCompiler.class);
        File pluginDirectory = new File(jar.getAbsolutePath().substring(0, jar.getAbsolutePath().length() - jar.getName().length()));
        String classes = buildClassPath(getJar(Bukkit.class).getAbsolutePath(), pluginDirectory.getAbsolutePath() + "/*");
        optionList.addAll(Arrays.asList("-classpath",classes));
        boolean success;
        try (StandardJavaFileManager fileManager = compiler.getStandardFileManager( null, null, null )) {
            Iterable<? extends JavaFileObject> units;
            units = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(file));
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, optionList, null, units);
            success = task.call();
        }
        if(success) {
            return new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - 5) + ".class");
        }
        else {
            return null;
        }
    } catch (IOException ex) {
        Logger.getLogger(RuntimeCompiler.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
private static String buildClassPath(String... paths) {
    StringBuilder sb = new StringBuilder();
    for (String path : paths) {
        if (path.endsWith("*")) {
            path = path.substring(0, path.length() - 1);
            File pathFile = new File(path);
            for (File file : pathFile.listFiles()) {
                if (file.isFile() && file.getName().endsWith(".jar")) {
                    sb.append(path);
                    sb.append(file.getName());
                    sb.append(System.getProperty("path.separator"));
                }
            }
        } else {
            sb.append(path);
            sb.append(System.getProperty("path.separator"));
        }
    }
    String s = sb.toString();
    s = s.substring(0,s.length() - 1);
    return s;
}

其他相關連接:
https://dzone.com/articles/how-to-compile-a-class-at-runtime-with-java-8-and
http://www.rgagnon.com/javadetails/java-0039.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章