Java - Use classes in a JAR

by
Jeremy Canfield |
Updated: September 16 2022
| Java articles
A JAR (Java Archive) is a file that contains classes. As an example, let's say sample.jar file has the following classes.
com/example/Hello.class
com/example/World.class
This means the Hello.class and World.class are in the com.example package. For example, perhaps Hello.class has the following.
package com.example;
public class Hello {
public static void hello( ) {
System.out.println("Hello");
}
}
And perhaps World.class has the following.
package com.example;
public class World {
public static String world( ) {
return "World";
}
}
Apps can be configured to use one or more of the classes in the JAR. For an app to be able to use a class in the JAR, the app needs to be able to access the JAR. There are 3 ways an app can access the JAR.
- Place the JAR file in the applications WEB-INF/lib folder
- Place the JAR file in the application servers classpath
- Place the JAR in a shared library
Each of these options are described in more depth in this article.
And here is an example of how an app may use com.example.Hello.class and com.example.World.class.
public class bar {
public static void main(String[] args) {
com.example.Hello.hello();
System.out.println(com.example.World.world());
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at