Cabe
Cabe is a Java byte code instrumentation tool that inserts checks based on JSpecify annotations into your class files.
According to the Fail-Fast Principle, all invalid input should be detected and reported early. Cabe helps you doing this by automatically checking method and constructor parameters.
Cabe also helps you during develompment by checking return values of methods.
What are JSpecify Annotations?
JSpecify is a project that aims to enhance Java code by providing a set of annotations specifically designed to improve code quality and facilitate better type-checking. These annotations help developers specify nullability and (later) other type-related constraints more precisely, allowing for more robust and error-free code. This ultimately leads to improved documentation, better IDE support, and more reliable results during static analysis.
You can find more details about JSpecify on their official website.
What does Cabe do?
Cabe analyzes your classes byte code and injects code that checks for violations of the nullability rules you added to your code by using JSpecify annotations.
Let's look at an example (use ./gradlew :examples:hello:run
to execute):
The contract of sayHello(@NonNull String name)
is that name
must have a non-null value when called. When you run this code through Cabe, using the standard configuration, an automatic null-check will be inserted, and when you run the program, you will see this:
You can of course obtain the same result by using this code:
Have a look at hellofx
for another example. In this example, the program is trying to read a resource from the classpath that can not be found. When not using Cabe, the stack trace will look like this:
The stacktrace indicates an error happened inside a JavaFX method, two methods down in the stack, our method loadImage()
appears. When we now open our IDE and look at the actual code, it becomes apparent that the real problem lies in getResourceAsStream()
returning null
and not a valid streeam.
Now what happens if Cabe is used? We will get this stacktrace:
Note that the cause now points directly at the exact method that returned the invalid null
value. This is of course a rather trivial example, but it shows how Cabe can simplify your workflow.
Will using Cabe impact performance?
Depending on the configuration used, there may be a minor overhead. Depending on your requirements, you can use different configurations.
During development, it is recommended to enable all checks so that programming errors will show up during early testing.
Once you are certain your project is thoroughly tested, you can restrict parameter checking to methods called by third-party code. When the standard setting is used, parameters to private API methods are checked using standard assertions that can be enabled or disabled at runtime. Standard assertions are usually optimized out by the JIT compiler when assertions are disabled. There may still be a minor impact due to increased class file size.
You can also disable all checks by using the
NO_CHECK
configuration and there will be no performance hit at all. Be aware that you might trade correctness to speed in this case as invalid inputs will not be detected.
When in doubt, profile your application when compiled using the different settings.
How are Null Checks implemented?
This depends on the configuration used. There are four types of checks. The examples assume a non-nullable parameter #named p
.
Check | Equivalent Java code |
---|---|
NO_CHECK | [N/A] |
STANDARD_ASSERTION |
|
ASSERT_ALWAYS |
|
THROW_NPE |
|
THROW_IAE |
|
Public vs Private API
When developing a library, you can configure different checks for:
the public API of your library so that invalid parameter values are detected when the user of your library calls your code with disallowed
null
values for a parameter,the private API of your library, i.e., code that cannot be directly called by users of your library.
What are the predefined configurations?
The predefined configurations are:
Name | Public API | Private API | Return Values |
---|---|---|---|
DEVELOPMENT | ASSERT_ALWAYS | ASSERT_ALWAYS | ASSERT_ALWAYS |
STANDARD | THROW_NPE | ASSERT | NO_CHECK |
NO_CHECK | NO_CHECK | NO_CHECK | NO_CHECK |
Things to note
Here are some points that you should be aware of when using Cabe.
Records
Cabe supports Java Records.
Do I need to explicitly add a Record Constructor so that Parameters can be checked?
No, Cabe adds the checks by evaluating the record declaration:
Standard Assertions cannot be generated for Record classes
Cabe currently cannot inject standard assertions into record classes because of technical restrictions. That is why for records, THROW_NPE is used instead of ASSERT. ASSERT_ALWAYS works as it does for other classes.
Technical background
Standard assertions use a special boolean flag $assertionsDisabled
that is initialised by the JVM when the class is loaded to the value obtained by calling Class.getDesiredAssertionStatus()
.
For classes that do not contain any assertions in their source code, this flag is not present in the class file and has to be injected into the byte code. the initialisation is then done in a static initializer block. This does not work for records and results in an InvalidClassFileException
.
Arrays
Cabe will detect when null
is passed for a non-nullable array parameter. It will however not detect null values contained in an array.
Generics
Cabe will detect violations for generic parameters when it can be determined at compile time that a type is non nullable:
If cannot check parameters where the nullability can not be determined at compile time:
SpotBugs
If you use SpotBugs in your build, it may report unnecessary null checks, i.e., when Cabe is configured to check method return values and SpotBugs byte code analysis infers the checked value will be non-null anyway. In that case, you might want to use a SpotBugs exclusion file.
Using Cabe in your Gradle Build
Cabe can be used either as a standalone program that you can run manually to instrument your class files or as a Gradle plugin that runs automatically in your build process. Let's see how it is done with Gradle.
To use Cabe in your Gradle build, add the plugin to your build script and configure the plugin:
This will run the Cabe processor in your build. When no configuration is given, a standard configuration is used.
Configure the Cabe Task
To configure the instrumentation, you can configure Cabe like this to use one of the predefined configurations:
If you omit the configuration block in your build, the standard configuration will be used.
Using different Configurations for Development and Release Builds
You can also automatically select a configuration based on your version string. In this example, strict checking is done for snapshot and beta versions whereas a release build will use the standard configuration:
Defining Custom Configurations
You can define a custom configuration that differs from the provided predefined configurations by providing a configuration String:
When using a configuration String, you can use either
a predefined name: "STANDARD", "DEVELOPMEN", "NOCHECKSS"
a single Check to be used public and private API and return values
multiple combination of keys ("publicApi", "privateApi", "returnValue") and checks; in this the remaining will be set to "NO_CHECK"
Examples:
Configuration String | Public API | Private API | Return Value |
---|---|---|---|
"STANDARD" | THROW_NPE | ASSERT | NO_CHECK |
"DEVELOPMENT" | ASSERT_ALWAYS | ASSERT_ALWAYS | ASSERT_ALWAYS |
"NO_CHECKS" | NO_CHECK | NO_CHECK | NO_CHECK |
"THROW_NPE" | THROW_NPE | THROW_NPE | THROW_NPE |
"ASSERT" | ASSERT | ASSERT | ASSERT |
"ASSERT_ALWAYS" | ASSERT_ALWAYS | ASSERT_ALWAYS | ASSERT_ALWAYS |
"NO_CHECK" | NO_CHECK | NO_CHECK | NO_CHECK |
"THROW_NPE" | THROW_NPE | THROW_NPE | THROW_NPE |
"publicApi=THROW_NPE" | THROW_NPE | NO_CHECK | NO_CHECK |
"publicApi=THROW_NPE:returnValue=ASSERT" | THROW_NPE | NO_CHECK | ASSERT |
"publicApi=THROW_IAE:privateApi=ASSERT" | THROW_IAE | ASSERT | NO_CHECK |
You can also use the standard record constructor of Configuration
Using as a Cabe as a standalone Command Line Tool
The instrumentation is done by the ClassPatcher
class. A precompiled runnable Jar that includes all necessary dependencies can be downloaded from Maven Central Repository and run using java -jar
:
What Java version is Cabe compatible with?
Cabe needs at least Java 17 to run. The instrumentation should work for class files from Java 11, but I have only tested this with versions 17 to 23.
Is there a Maven Plugin for Cabe?
Not yet. But it's on my Todo list.
Is the Source available?
Sourcecode is available under the MIT license on the project GitHub page.
Where do I report Bugs?
Use GitHub issues to report Bugs and suggestions.
What about the Name?
In Javanese, both cabe and lombok refer to chili peppers. At the same time, Lombok is a... well, it's something between a library and a language on its own that extends Java with certain features. One of these features are annotations to mark nullable and non-nullable types and code instrumentation to do runtime checks based on these annotations.
While widely used, Lombok is quite controversial - you will find plenty of discussions on this topic on the internet.
Newer Java versions brought many features that developers used Lombok for, perhaps most notably Java records. But having automated null checks in your code is one Lombok feature that I liked but could not find any non-Lombok alternative. That's why I started Cabe, and that's where the name comes from.