简体   繁体   English

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

[英]Dangers of using reflection to add files to classpath at runtime

Recently I have been looking for ways to dynamically load jar files into my application at runtime. 最近我一直在寻找在运行时将jar文件动态加载到我的应用程序中的方法。

I have come along a certain solution several times, which is basically a "hack" that gets the system classloader and uses reflection to access the otherwisep rotected addURL method in order to add additional files to the original classpath at runtime. 我已经多次使用某个解决方案,这基本上是一个“hack”,它获取系统类加载器并使用反射访问其他受保护的addURL方法,以便在运行时将其他文件添加到原始类路径中。 This solution supposendly works really well and avoids the problems that occur when writing and using a selfmade custom class loader. 这个解决方案非常有效,可以避免在编写和使用自制的自定义类加载器时出现的问题。

It looks something like this: 它看起来像这样:

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");
 }

My question is as follows: I assume there is a really good reason for making the addURL method protected in the first place, there must be some kind of pitfalls or dangers when adding files to the classpath dynamically. 我的问题如下:我假设有一个很好的理由让addURL方法首先受到保护,在动态地向类路径添加文件时必然存在某种陷阱或危险。

Besides assuming the system classloader is always a URLClassLoader, which "should always be the case" (TM), what kind of trouble could I run into when using this "hack"? 除了假设系统类加载器总是一个URLClassLoader,“应该总是这样”(TM),使用这个“hack”时我会遇到什么样的麻烦?

Thanks 谢谢

The primary danger is your relying on a run time check of the methods existence. 主要的危险是你依赖于存在的方法的运行时检查。

If the method signature changes in the future, you won't know about it till run time. 如果方法签名将来发生变化,那么直到运行时才会知道它。 This could also leave in a nasty situation if no alternative method is provided. 如果没有提供替代方法,这也可能留下令人讨厌的情况。

Also, as huge already states, the designers choose to make the method protected for a reason (other then lack of forethought) 此外,作为巨大的已经状态,设计师选择使方法protected是有原因的(除此之外缺乏预见)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM