最近我一直在寻找在运行时将jar文件动态加载到我的应用程序中的方法.
我已经多次使用某个解决方案,这基本上是一个"hack",它获取系统类加载器并使用反射访问其他受保护的addURL方法,以便在运行时将其他文件添加到原始类路径中.这个解决方案非常有效,可以避免在编写和使用自制的自定义类加载器时出现的问题.
它看起来像这样:
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");
}
Run Code Online (Sandbox Code Playgroud)
我的问题如下:我假设有一个很好的理由让addURL方法首先受到保护,在动态地将文件添加到类路径时必然存在某种陷阱或危险.
除了假设系统类加载器总是一个URLClassLoader,"应该总是这样"(TM),使用这个"hack"时我会遇到什么样的麻烦?
谢谢