在运行时使用反射将文件添加到类路径的危险

tho*_*nds 6 java reflection classloader

最近我一直在寻找在运行时将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"时我会遇到什么样的麻烦?

谢谢

Mad*_*mer 1

主要危险是您依赖于方法存在的运行时检查。

如果方法签名将来发生变化,您直到运行时才会知道。如果没有提供替代方法,这也可能导致糟糕的情况。

此外,正如巨大已经指出的那样,设计师选择这种方法是protected有原因的(除了缺乏深思熟虑之外)