问题
Sorry, maybe this question is too silly or already answered, but I couldn't find it out.
I'm wondering if there is some known Java class-loader that is able to accept remote files in the classpath, i.e., entries like CLASSPATH="http://somewhere.net/library.jar:...".
Note that I am not talking about applets or Java Web Start. Think of an application that can use different back-ends (e.g., MySQL, Oracle), I'd like to prepare the classpath in a shell script, based on the user's back-end preference and have the class-loader to download the needed jar (the jdbc driver in this example) from a distribution server. I'm not talking about Maven either (the user just gets the binary distribution, I don't want to force them to build what they need from the sources).
回答1:
The SystemClassLoader
is a URLClassLoader. You could try, I leave it to you:
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{new URL("http://somewhere.net/library.jar")});
Class.forName("your.remote.ClassName");
Let me know :)
回答2:
You could use an URLClassLoader, but it would download the file every time, and would make the code more complex.
If you're using a shell script already, why don't you simply use curl to download the jar and place it in the classpath?
回答3:
Class loading is a complex process. It's possible that the regular classpath ClassLoader is a URLClassLoader in all runtime environments on all platforms, but I assume it wouldn't necessarily have to be.
One method for adding classpath entries is to add a Class-Path: property to a jarfile's META-INF/MANIFEST.MF
file, and the space-separated values of that property are resolved with a URLClassLoader. (Maven adds some of its classpath entries to jarfile manifests as file://
URIs, implying that http://
or https://
would work too.) So even if you can't get URL-based classpath entries working in the normal Java classpath in some runtime environment, you should be able to get them working by specifying the URL in a manifest file.
(I'm not familiar with how Java WebStart works, but maybe that also makes use of URL-based classpath entries?)
来源:https://stackoverflow.com/questions/14247716/remote-jars-in-the-classpath