Add a File To Java Classpath At Runtime

My code accepts a zip file as input. 
I unpack several images from the zip file into a temp directory (literally, created by File.createTempFile()) 

I have another program that will load these images as resources and put them into the database *if* I can get the temp directory onto the class path. If I can do this I won't have to write new code. Once my program exits, the temp directory should be removed from the classpath. 

Is there a standard way of going about this? Or is it just a horrific idea? 

This works pretty well: 

You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

import java.io.IOException; 
import java.io.File; 
import java.net.URLClassLoader; 
import java.net.URL; 
import java.lang.reflect.Method; 

public class ClassPathHacker { 

private static final Class[] parameters = new Class[]{URL.class}; 

public static void addFile(String s) throws IOException { 
   File f = new File(s); 
   addFile(f); 
}//end method 

public static void addFile(File f) throws IOException { 
   addURL(f.toURL()); 
}//end method 
 

public static void addURL(URL u) throws IOException { 

  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"); 
  }//end try catch 

   }//end method 

}//end class 

PS: The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.