Building Java projects from the CLI – Part 3

In the final part of this tutorial we will add a third party jar to the classpath and use it in our main method.

STEP 1:

Create a lib directory at the root of our previous project. This is where third party libraries conventionally go in java projects so we will place our JAR here. Your project structure should look like below

lib project structure

STEP 2:

 

Now lets go and get the jar for the famous guava library by Google. You can find it here.

Make sure you have at least JDK 8 installed. If your not sure what that means exactly I wrote another post on that topic here.

After downloading the jar put it in your libs directory. Your project should look something like this now.

STEP 3:

 

Now lets add a method from the imported jar into our ClasspathDemo.java class. Our code in ClasspathDemo.java looks like this now

 

STEP 4:

Now lets compile this project. Run this command from the root of the classpath-demo-pt3 directory in the terminal.

Most of this command is explained in the previous posts. The new portion is that we put the jar on the classpath using the -classpath command. This allows the jvm to see the jar when it comes time to compile our source code. Now navigate into the classes directory.

STEP 5:

Now we can run our code with this following snippet.

This command tells us to look in the lib directory and the current directory for class files. The jvm now sees the jar file in the lib directory and the ClasspathDemo file in the current directory and it can run our code.

Thats it! I hope you enjoyed this 3 part series and now your a little more comfortable with what your IDE and build tools are doing when they build and run your projects.

Add a Comment

Your email address will not be published. Required fields are marked *