So, every Java text book talks about how flexible Java is since it can load classes at run time. Just cobble together a string and give it to Class.forName()
, and
Application Servers rely also heavily on ClassLoaders
to isolate the different deployed module. E.g.
Thanks to the magic of class loaders...
Plugins is the first thing that comes to mind. Java class loading makes it very easy compared to languages like C++.
One point that you may not be aware of is that any Java virtual machine heavily relies on class loading internally. Everytime a reference to, say, a method is seen by the bytecode interpreter, it checks whether the class the method belongs to is already loaded, and if it is not, loads it using the very same mechanism behind Class.forName()
before resolving the method. This mecanism is very powerful as any Java application truly acts as a set of replaceable components which are all dynamically loaded. If the VM is well written it can for instance load classes through a custom class loader that fetches classes from the network instead of regular files.
The class loading time depends on the virtual machine implementation, but most rely on this late-binding mechanism that loads a class the first time the VM meets it.
I use it when I'm building an off-the-shelf application that needs to be tailored by myself or the customer to meet the customer's specific requirements.
Well, I've used it for dynamically loading JDBC drivers into a J2EE application. Wheteher this could have been done a better way, I have no idea.
It was just easier at the time to do the forName()
call.
Using the dynamic class loading is also very useful for loading configuration files as Thilo mentions. More generally, dynamic class loading can make a nice file system abstraction layer in many situations, simplifying writing preference and config sensitive code. Just make sure the resource you need is on the classpath and load it as an InputStream.
Furthermore, with a custom protocol handler in Java it is possible to access items on the classpath via URL. This isn't an advantage specific to dynamic class loading, but it does demonstrate how classpath resources can be accessed via the same API as other resources (even remote ones). http://java.sun.com/developer/onlineTraining/protocolhandlers/
The Java classloader mechanism is powerful because it provides an abstraction point at exactly the point where code is loaded, which lets you do things such as:
On the point of modifying code during load, there are a world of interesting things you can do to remix your code - AOP, profiling, tracing, behavior modifications, etc. At Terracotta we relied on the classloader abstraction to dynamically load a class, then intercept all access to fields and dynamically add the ability to load state from the same object at a remote node in the cluster later. Cool stuff.