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.hasMoreElement s())
{
ZipEntry entry = (ZipEntry) allEntries.nextElement();
if (entry.getName().endsWith( ".class"))
{
byte[] classData = loadBytesFromStream(zipfil e.getInput Stream(ent ry),(int) entry.getSize());
if (classData != null)
{
// Define the class
Class c = defineClass(entry.getName( ),classDat a,0,classD ata.length );
// Resolve the class
resolveClass(c);
}
}
}
}
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.hasMoreElement
{
ZipEntry entry = (ZipEntry) allEntries.nextElement();
if (entry.getName().endsWith(
{
byte[] classData = loadBytesFromStream(zipfil
if (classData != null)
{
// Define the class
Class c = defineClass(entry.getName(
// Resolve the class
resolveClass(c);
}
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
Or have a look at the URLClassLoader class, it should also do what your after.