TreeConstants is a simple annotation processor that can turn occurances of string literals in code (like "java.io.tmpdir"
or "ui.view.main"
) into refactorable, typo-safe, documentable field references.
The sole objective of TreeConstants is to transform calls like this:
System.getProperty("java.io.tmpdir");
into calls like this:
System.getProperty(java.io.tmpdir);
The annotation processor creates two nested classes (java.io
) and a field (tmpdir
). Your code can then use java.io.tmpdir
exactly as "java.io.tmpdir"
without caring where the class hierarchy actually resides. Since javac
automatically inlines static final
fields, there's zero runtime performance impact from using TreeConstants. To prove the point, the classes generated by the annotation processor don't even need to be included in your resulting artifact (since they will never be loaded anyway).
Here are some advantages of using TreeConstants:
- Compile-time typo detection
- Autocompletion and documentation support within IDEs
- Allows for more powerful refactoring operations than find-and-replace for string literals
Here are some disadvantages of using TreeConstants:
- Eclipse doesn't fully support Gradle annotation processors yet (apply
net.ltgt.apt-eclipse
plugin in the meantime) - Although runtime isn't affected, the build process will be slowed down by the annotation processor
Custom Constant Trees
java.io.tmpdir
was just an illustrative example. The real utility of TreeConstants is defining your own constants:
/**
* The current view type.
*/
@TreeConstant
private static final String ui_view_main = "ui.view.main";
/**
* The filesystem read permission.
*/
@TreeConstant
private static final int permission_fs_read = 102;
This example shows that any static final
field can become a tree constant by annotating it with @TreeConstant
. The underscore-separated name of the field determines the tree structure (so ui_view_main
will become ui.view.main
). The field's value will replace all references to the tree constant in code.
Gradle Usage
To include TreeConstants in a Gradle project, add the following dependencies to your build.gradle
:
// Contains the @TreeConstant annotation
compileOnly 'com.github.cilki:tree-constants-api:+'
// The annotation processor
annotationProcessor 'com.github.cilki:tree-constants:+'
Or if you just want a set of tree constants for the JDK (like "java.io.tmpdir"
and so on):
compileOnly 'com.github.cilki:tree-constants-common:+'