Reasons for Sealing a .jar and How to Verify It

javaSecurity

I have created a sealed jar, but I don't see difference compared to using a non-sealed one.

  • What tests I can perform to verify the jar is sealed?
  • What reason we could have to prefer using a sealed over non one?
  • Will a sealed create any trouble to users of my projects?

Best Answer

You can test that a jar is sealed by defining a class to exist in a package used in the jar file. If the jar is sealed, all packages are normally sealed, else you can seal them on a per-package basis. The class you create should then try to access protected or default members of a class in that package.

For example, if the jar has a class com.example.Widget where the package com.example is sealed and Widget has protected/default members, create a class com.example.Test that attempts to access those members. This should fail.

The reason for sealing follows from a description of how to test it: you want your code to be self-contained and users of the jar should only use public members. Packages are not required to be unique across jars (and bin folders in your IDE) used by a program. You are able to define a class in the same package as in a jar and access protected/default members that might cause problems. Often, default visibility is used as an analog to C++'s friend keyword by allowing other classes in the same package the ability to perform actions that are only safe because the same programmers work on both classes and understand their internals. Perhaps a default visibility method forgoes some bounds checking in the name of performance, with the understanding that client code will never access it. For example, the String class in Java has a few of these types of methods since String handling has to be lightning-fast because a large amount of code relies on it. BigDecimal is built on top of BigInteger and uses default access to optimize a few operations that other users of the class ought not to use.

TL;DR: Classes in the same package might access non-public members of each other for performance or simplicity. This access might not check invariants and preconditions. One can put classes in the same package in multiple locations in the classpath. Sealing a package or jar restricts client code from accessing these methods, because it might break stuff otherwise.

This will not cause any problems for users of the jar. The classloading mechanism that accesses resources (e.g. class files) in jars fully supports sealed jars and packages.

Related reading: Sealing Packages within a JAR File

Related Topic