Add JAR files programmatically to the classpath

Everyone knows that starting a Java application from the command line is, to say the least, annoying. Ever got an application that contained several JAR files but no batch file or shell script to start the application?

You may have ended up creating a batch file like this:
java -classpath lib/abc.jar;lib/def.jar ...

A better approach is to collect the necessary JAR files with batch files or a shell script like this: (Thanks to the guys from iReport for the above code.)

If you are a lucky one, you may have had the opportunity to use Java 6, which introduced a wildcard option: java -classpath lib\* ...

But what if you create your own application and you have to load some libraries “on the fly”. At first this may seem difficult or impossible but, in fact, it’s easy:

  1. Start your application with a single main JAR file:
    java -classpath mymain.jar ...
  2. Add more JAR files programmatically:

Simple, isn’t it?

You can find the Utils4J library here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s