Java jar seal packages With Examples

Java JAR provides option to seal the package. Java jar seal package means that if any program is using that jar then all the classes should be loaded from that jar itself. Any attempt to load the classes from other jar files will throw java.lang.SecurityException. The documentation for sealing jar packages seems confusing, so we will learn this feature with sample programs.

Java jar seal packages

For effect of jar package sealing, we need at least two jar files to use in a test program. Below image shows two java project I have with same package names but with different classes.

Read following posts to know how to create jar from java classes and how to run jar file in java.

java-jar-seal

For sealing packages in a jar, we need to add it’s entries in jar manifest file. So I have the manifest file with following content.

manifest.txt

Now I run following commands in both projects to generate two jar files with above manifest entry.

Java jar seal packages effect

Now I will write a sample program that will use both these jar files to show the effect of java jar sealing.

So MyClass is trying to load class A from jar file seal1.jar and class B from seal2.jar. Let’s try to compile and run this class and see what happens.

As you can see that it throws java.lang.SecurityException at runtime with error message as “package is sealed“.

Jar package sealing helps us in making sure that all the classes are loaded from same version of jar file.

Tip: If you want all the packages of a jar file to be sealed, you can just add entry for Sealed as true. To exclude any package from sealing, you can add an extra entry with Sealed as false.

MANIFEST.MF

That’s all about java jar sealing packages.

Reference: Oracle Doc

By admin

Leave a Reply