且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在运行时将文件添加到java类路径

更新时间:2023-01-10 18:15:43

您只能将文件夹或jar文件添加到类加载器。因此,如果您有一个类文件,则需要先将其放入相应的文件夹结构中。

You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

这里是一个相当丑陋的黑客,它在运行时添加到SystemClassLoader:

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

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

访问受保护的方法 addURL 需要反射。如果存在SecurityManager,则可能会失败。

The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.