Search code examples
javaclassloader

What do people use class loading for?


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 catch the ClassNotFoundException and handle it. So much for the theory.

Can you give examples of how you've been using Java class loading to achieve a feature which otherwise wouldn't have been possible or easy? Note that I'm not asking "what great things could we do?" - I'm looking for real-world examples, be it an open-source application or - if you can describe this without giving out too much details - a proprietary application.

Edit: Sure, the VM loads classes lazily as it needs them. That's a behind-the-scenes thing as long as I'm sure that all classes I'll ever need are there. How do I handle a ClassNotFoundException? Suppose I've written ten pages worth of text, and the PrinterDriver class can't be found.


Solution

  • 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.