Java Jar File As Stream Class Loader
How can I load classes from a jar file stored as a 开发者_StackOverflowblob in a database as the URL Class loader only accept a URL or file path?
Implement your own subclass from java.lang.ClassLoader
that does the loading from the database.
Maybe this post helps to get started: http://www.javablogging.com/java-classloader-2-write-your-own-classloader/
Writing your own ClassLoader can be quite confusing, especially for a beginner. I recently needed to load some jars dynamically and found this answer very helpful. It explains how to use ResourceFinder, a class from Apache xbean or something. It's a single file that you can easily drop into your project.
Most advantageously for your situation, although ResourceFinder loads by URL, the readContents
function (used to actually load up the jar file) looks like this:
private String readContents(URL resource) throws IOException {
InputStream in = resource.openStream();
BufferedInputStream reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedInputStream(in);
int b = reader.read();
while (b != -1) {
sb.append((char) b);
b = reader.read();
}
return sb.toString().trim();
} finally {
try {
in.close();
reader.close();
} catch (Exception e) {
}
}
}
which could easily be modified to work on any Stream/blob you have. Some minor changes to the class could, I'm sure, make it do exactly what you want, or at the very least point you in the right direction. Writing ClassLoaders from scratch is no fun.
EDIT: Y'know, I've just taken another look, and I'm not so sure that you could get away with only minor changes to ResourceFinder. Still, look it over, see what you can get from it.
If you look at the code for JarClassLoader in the Java tutorial that will get you started.
There are also other resources available if you Google for Jar Class Loader.
You will need to modify the code to pass in the ByteStream that you have obtained from the BLOB in the DB.
implementing your own classloader is the obvious answer. depending on how you need to use the classes that could be problematic. another, lesser known option, would be to implement your own url handler. you could come up with a custom url scheme like "db://<dbname>/<tablename>/<jarfile>"
or something. you would implement a custom URLStreamHandler, details here.
one way to laod jar file .. it may helpful to you.
public class JarLoad {
public static void main(String[] args) throws ZipException, IOException {
File jarfile = new File("C\\scan.jar");
if(! jarfile.isDirectory()){
ZipFile jar = new ZipFile(jarfile);
Enumeration enumeration = jar.entries();
while(enumeration.hasMoreElements()){
ZipEntry zipEntry = (ZipEntry)enumeration.nextElement();
System.out.println(zipEntry.getName());
}
}
}
}
精彩评论