博客主机
A-A+

Modify Classpath At Runtime

2008年12月04日 柴房 暂无评论

I've seen a lot of forum posts about how to modify the classpath at runtime and a lot of answers saying it can't be done. I needed to add JDBC driver JARs at runtime so I figured out the following method.

The system classloader (ClassLoader.getSystemClassLoader()) is a subclass of URLClassLoader. It can therefore be casted into a URLClassLoader and used as one.

URLClassLoader has a protected method addURL(URL url), which you can use to add files, jars, web addresses - any valid URL in fact.

Since the method is protected you need to use reflection to invoke it.

Here's some code for a class which adds a File or URL to the classpath:


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


http://forums.sun.com/thread.jspa?threadID=300557&start=0&tstart=0

以上时关于这个方法的一些讨论,令人恍然大悟

标签:

给我留言

Copyright © 小小的数据技术梦想 保留所有权利.   Theme  Ality 浙ICP备12043346号-1

用户登录

分享到: