So, you’ve inspected your Java code in any possible way, using Findbugs, Checkstyle, PMD, Crap4J and many other tools. You know every number by heart and keep a sharp eye on its trend. But what about some simple questions you might ask yourself about your project, like:
- How many instance variables aren’t final?
- Are there any setXYZ()-methods without any parameter?
- Which classes have more than one constructor?
Each of this question isn’t of much relevance to the project, but its answer might be crucial in one specific situation.
Using QDox for throw-away tooling
QDox is a fine little project making steady progress in being a very intuitive Java code structure inspection API. It’s got a footprint of just one JAR (less than 200k) you need to add to your project and one class you need to remember as a starting point. Everything else can be learnt on the fly, using the code completion feature of your favorite IDE.
Let’s answer the first question of our list by printing out all the names of all instance variables that aren’t final. I’m assuming you call this class in your project’s root directory.
public class NonFinalFinder { public static void main(String[] args) { File sourceFolder = new File("."); JavaDocBuilder parser = new JavaDocBuilder(); builder.addSourceTree(sourceFolder); JavaClass[] javaClasses = parser.getClasses(); for (JavaClass javaClass : javaClasses) { JavaField[] fields = javaClass.getFields(); for (JavaField javaField : fields) { if (!javaField.isFinal()) { System.out.println("Field " + javaField.getName() + " of class " + javaClass.getFullyQualifiedName() + " is not final."); } } } } }
The QDox parser is called JavaDocBuilder
for historical reasons. It takes a directory through addSourceTree()
and parses all the java files it finds in there recursively. That’s all you need to program to gain access to your code structure.
In our example, we descend into the code hierarchy using the parser.getClasses()
method. From the JavaClass
objects, we retrieve their JavaFields
and ask each one if it’s final, printing out its name otherwise.
Praising QDox
The code needed to answer our example question is seven lines in essence. Once you navigate through your code structure, the QDox API is self-explanatory. You only need to remember the first two lines of code to get started.
The QDox project had a long quiet period in the past while making the jump to the Java 5 language spec. Today, it’s a very active project published under the Apache 2.0 license. The developers add features nearly every day, making it a perfect choice for your next five-minute throw-away tool.
What’s your tool idea?
Tell me about your code specific aspect you always wanted to know. What would an implementation using QDox look like?