簡體   English   中英

我們如何借助Java代碼來設置類路徑?

[英]How we can set the class path with the help our java code?

我們如何借助Java代碼而不是手動設置類路徑?

我們不能。 必須在Java虛擬機啟動時設置類路徑。 我們無法從正在運行的應用程序中更改它。

可以從不在類路徑中的位置和jar文件加載類。 您可以使用URLClassloader從已知(File-)URL加載單個類,也可以實現自己的類加載器以獲取更多樂趣。

如果要編輯類路徑以從其他路徑加載jar文件,則可以使用該類路徑,然后使用URLClassLoader(如@Andreas_D建議)執行以下代碼可能對您有幫助:

import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;

public class ClassPathHacker {

private static final Class[] parameters = new Class[]{URL.class};

public static void addFile(String s) throws IOException {
   File f = new File(s);
   addFile(f);
}//end method

public static void addFile(File f) throws IOException {
   addURL(f.toURL());
}//end method


public static void addURL(URL u) throws IOException {

  URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
  Class sysclass = URLClassLoader.class;

  try {
     Method method = sysclass.getDeclaredMethod("addURL", parameters);
     method.setAccessible(true);
     method.invoke(sysloader, new Object[]{u});
  } catch (Throwable t) {
     t.printStackTrace();
     throw new IOException("Error, could not add URL to system classloader");
  }//end try catch

   }//end method

}//end class

暫無
暫無

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

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