1

In which case one would use a URLClassLoader to load a class from a specific jar in a specified path?
E.g.

URL url = new URL("file:///path/to/customClasses.jar");
URLClassLoader pluginLoader = new URLClassLoader(new URL[] { url });
Class<?> cl = pluginLoader.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 use apackage.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!

Cratylus
  • 52,998
  • 69
  • 209
  • 339
  • Say you wanted to be able to load code created or loaded dynamically, after the program started. You can load a different version of this jar later as well or instead of this one. – Peter Lawrey Dec 29 '10 at 17:43
  • @Peter Lawrey:I am sorry but I don't understand what you mean when you say "load code creater/loaded dynamically" – Cratylus Dec 29 '10 at 17:47
  • @user384706, say you have a dynamically loaded application which needs common-logging v1.0, later you load an application which need commons-logging v1.1. You can drop the first library or have them both loaded with custom loaders. – Peter Lawrey Dec 29 '10 at 21:10
  • @Peter Lawrey:I understand what you say in a vague manner.I am not sure the context you are referring.Your example is an application loads another application and all it's dependent libraries? Could you please give me a specific example to get this in my head? – Cratylus Dec 29 '10 at 21:30
  • yes, Web servers and OSGi frameworks all have custom class loaders. – Peter Lawrey Dec 29 '10 at 22:05
  • @Peter Lawrey:So it is useful only in this cases?When building such frameworks? – Cratylus Dec 29 '10 at 22:20
  • A custom class loader is only useful when you want to control how classes are loaded programmatic-ally. Is there another usage you are looking for? – Peter Lawrey Dec 30 '10 at 01:18

1 Answers1

2

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

Will
  • 6,179
  • 4
  • 31
  • 49