web項目部署后動態編譯無法找到依賴的jar包


很納悶的一個問題,通過配置文件生成的java源碼在本地動態編譯沒有問題,但是部署服務器后編譯不通過,找不到依賴的jar包。

通過網上查資料,找到一個兄弟提供的方法,問題解決了;下面貼出代碼以供參考:

package com.songxingzhu.utils.compile;
import org.apache.commons.io.FileUtils;
import com.songxingzhu.utils.context.AppContext;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class ClassBuilder {
    public static Class<?> buildClass(String fullClassName, String codeFilePath) throws IOException, ClassNotFoundException {
        return buildClass(fullClassName, codeFilePath, "UTF-8", AppContext.baseDirectory());
    }
    public static Class<?> buildClass(String fullClassName, String codeFilePath, String charsetName, String buildOutput) throws IOException, ClassNotFoundException {
        try {
            String code = FileUtils.readFileToString(FileUtils.getFile(codeFilePath), charsetName);
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            JavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
            List<JavaFileObject> files = new ArrayList<>();
            files.add(new JavaSourceFromCodeString(fullClassName, code));
            List<String> options = new ArrayList<>();
            options.add("-classpath");
            StringBuilder sb = new StringBuilder();
            URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
            for (URL url : urlClassLoader.getURLs()) {
                sb.append(url.getFile()).append(File.pathSeparator);
            }
            options.add(sb.toString());
            options.add("-d");
            options.add(buildOutput);
            // execute the compiler
            boolean isok = compiler.getTask(null, fileManager, null, options, null, files).call();
            if (isok) {
                File root = new File(buildOutput);
                if (!root.exists()) root.mkdirs();
                URL[] urls = new URL[]{root.toURI().toURL()};
                ClassLoader classLoader = ClassBuilder.class.getClassLoader();
                Class<?> clazz = Class.forName(fullClassName, true, classLoader);
                return clazz;
            }
            return null;
        } catch (Exception ex) {
            throw ex;
        }
    }
}
 
個人理解:部署后不像eclipse編譯有.classpath指向依賴的所有的jar,需要自己組裝類似classpath,指定jar包路勁。重點是設置option,不懂option的可以通過cmd命令查看javac的參數介紹。
其中,option.add("-classpath");就是類似直接運行javac -classpath 類文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM