Load your CLASSPATH at runtime

One of the great advantages of programming in JAVA is the ability to add to your code as you go. You can create classes and turn them into packages which can then be imported and used in any other JAVA application. Each instance of your program relies on the CLASSPATH environment variable for external packages. For example you can import an external JDBC driver for your application to connect your database. You can also import dynamic modules to add and change program functionality. Setting the classpath variable can be done as a part in the environment variables or while invoking the JVM. However, when your program relies on external web updates, it’s not practical to change the command arguments every time there is a major update. In this article, we are going to explore programmically changing your classpath to modify program features. We are going to assume you have an updater module that basically drops all of your JAR files into the module’s directory. We are then going to read all the files in the directory and add them to your classpath at run time. The code to reading all the files in the directory looks like this:

And the last step is to append the files to the classfile.

It is very important to program your classpath as the first step when you invoke your program. Any objects that are being initialized before the classpath is set can result in a no class definition error. You’ve seen how useful it can be to any software that relies on external packages. The possibilities are endless. Happy programming!

Source