Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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. 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.

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"?

Thanks

like image 749
thousands Avatar asked Oct 27 '12 17:10

thousands


1 Answers

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)

like image 75
MadProgrammer Avatar answered Sep 30 '22 12:09

MadProgrammer