Link to home
Start Free TrialLog in
Avatar of nixj14
nixj14

asked on

Dynamically adding jars to classpath

Okay, I have found it to be a necessity to modify my classpath midstream for a particular installer that I am writing.  I will be prompting the user for a few custom directories, and then pulling the necessary jars from these directories into my current classpath/classloader.  

Here's what I know...There is no way to just add a jar file to your current classpath/classloader.  What I've found that you have to do is for each JarEntry in the jar, get its InputStream, define a class out of that byte array, and then load that class into the current classloader.  Sounds reasonable.

Here's what I don't know...How do you handle classes that have inner classes?  

Here's a code snippet that I'm using:

File file = new File(pathToJar);
ZipFile zipfile = new ZipFile(file);

try
{
 Enumeration allEntries = zipfile.entries();
 while (allEntries.hasMoreElements())
 {
  ZipEntry entry = (ZipEntry) allEntries.nextElement();
  if (entry.getName().endsWith(".class"))
  {
   byte[] classData = loadBytesFromStream(zipfile.getInputStream(entry),(int) entry.getSize());
                         
   if (classData != null)
   {
    // Define the class
    Class c = defineClass(entry.getName(),classData,0,classData.length);
    // Resolve the class
    resolveClass(c);
   }
  }
 }
}
ASKER CERTIFIED SOLUTION
Avatar of Venci75
Venci75

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mick Barry
You could simply extract all the class into a directory in your classpath and not worry about loading all the classes using the classloader.

Or have a look at the URLClassLoader class, it should also do what your after.
Avatar of nixj14
nixj14

ASKER

Appreciated that a lot.  Never really thought about the fact that you could extract the classes and then define them.  
Implementing a new class loader seems to be reinventing the wheel a bit to me.