java urlclassloader usage.Is it needed only in some rare cases?
In which case one would use a URLClassLoader
to load a class from a specific jar in a specified path?
URL url = new URL("file:///path/to/customClasses.jar");
URLClassLoader pluginLoader = new URLClassLoader(new URL[] { url });
Class<?> cl = pluginLoad开发者_Python百科er.loadClass("apackage.MyCustomClass");
If I wanted to use classes from customClasses.jar, I always thought that placing this jar in a path accesible from CLASSPATH is enough.
Then in my code just useapackage.MyCustomClass
.
I think I have something missunderstood or missing here, so could someone please explain and give an example of when the above snippet of loading class this way is useful?
Thanks!I would say that depending on the type of programming you are doing, the use of the URLClassLoader
should be a very rare occurrence.
Typically you will use the class loader for loading in classes at runtime that you couldn't anticipate in advance.
A good example is if you build a tool that can be extended with plugins, and the plugins are loaded at runtime. For example, Eclipse.
If you have the jar available at compile time and are on a command line, add the needed jar file to your compile statement. For example,
javac -cp /path/to/lib/customClasses.jar MyClassThatReferencesCustomClasses
If you're using Eclipse, add the jar to your project, and right click on it and select add to build path.
Regards,
Will
精彩评论