簡體   English   中英

使用Toolprovider編譯類並使用ClassLoader加載類

[英]Compiling classes with Toolprovider and loading them with ClassLoader

我正在嘗試加載在運行時生成編譯的類。 我可以使用以下代碼毫無問題地對其進行編譯:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

List<File> sourceFileList = new ArrayList<File>();
sourceFileList.add(new File(sourceFile));
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFileList);
CompilationTask task = compiler.getTask(null, fileManager, null, null,null, compilationUnits);

但是我不明白如何加載我已經編譯的類(或在哪里編譯)以供后用。 我已經嘗試過幾種方法,例如:

Class type = ClassLoader.getSystemClassLoader().loadClass(className);

要么

ClassLoader loader = URLClassLoader.newInstance(new URL[] { myUrl }, getClass().getClassLoader());  //(URL?)

沒有成功(我不明白這些...)。 您能幫我還是舉個簡單的例子,以便我可以發展呢?

提前致謝。

您最后一次嘗試應該可以。 myUrl應該引用包含生成的.class的目錄(或Jar)。

myUrl = new URL("file:///myGeneratedCode/");

該網址必須以"/"結尾才能被視為目錄,否則,它將采用一個Jar文件。

我終於找到了“問題”。 從我的角度來看這是一個愚蠢的錯誤:我試圖在關閉生成的Java文件之前對其進行編譯。 令人討厭的是JavaCompiler沒有引發任何異常。

解決了這個問題並生成了類后,使用ClassLoader加載它就不再有問題

再次感謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM