How to print current project classpath

Imagine you want to figure out what is the path to your Java compiled classes. For that, you will need to print the classpath. This article is a short explanation of what a classpath is and a single line of Java code that will help you print out your classpath.

What is Java classpath?

If we want to be wordy, classpath is the path where the Java Virtual Machine looks for user-defined classes, packages, and resources in Java programs. However, plain and straightforward, classpath is the route where the Java Virtual Machine will know where to find your compiled class.

Think of classpath as Java’s version of PATH environment variables – OSes search for executable files on the system environment PATH, Java searches for classes and packages on the classpath.

It would generally be impractical to have the JVM look through every folder on your machine. So you have to provide the JVM with a list of places where to look. Then, when we place folders and jar files on the classpath, we can automatically look up classes.

How to print classpath?

In Java, we can use a single line of code to print out the current project classpath. The only issue is with the system based classpath separator. On Unix based systems (Mac OS, CentOS, etc.), the colon character : is the classpath separator. However, on Windows, the separator is the semicolon ;.

To print classpath at Unix based systems use:

System.out.println(System.getProperty("java.class.path").replace(':', '\n'));

To print classpath at Windows use:

System.out.println(System.getProperty("java.class.path").replace(';', '\n'));

Output

The code will work like a charm in new versions of Java (8, 11, …). However, the Java code snippet will also print library dependencies.

On Windows, the output can look something like the following example:


C:\DEV\programming\interview-preparation\trees\target\test-classes
C:\DEV\programming\interview-preparation\trees\target\classes
C:\Users\computer_user\.m2\repository\junit\junit.13.1\junit-4.13.1.jar
C:\Users\computer_user\.m2\repository\org\hamcrest\hamcrest-core.3\hamcrest-core-1.3.jar
C:\Users\computer_user\.m2\repository\org\projectlombok\lombok.18.12\lombok-1.18.12.jar
...

Note: If you have a better idea for printing classpath, let us know in the comments below.

Conclusion

Concisely, this article summarized what the classpath is and how to print classpath in your current Java project.

Did you find printing classpath easy? Do you have your trick or know another way how to print classpath? Let us know in the comments below the article. We would like to hear your ideas and stories.

This entry was posted in Tips & tricks and tagged , , . Bookmark the permalink.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.