Finding unused code in Java projects
In many projects, especially big ones, developed over several years, there is a lot unused code. Cleaning up projects and deleting such unused code is important.
- Eclipse can detect unused methods and variables.
- PMD (and PMD maven plugin) can also do this and even be integarated into CI process.
- Eclipse Core Tools plugin can find unused classes (see description here).
Unfortunately all above methods will mark code invoked by reflection (e.g. using IoC container such as Spring) as unused. At the same time garbage code that was left behind together with its unit test won’t be detected.
I see only one way to detect such obsolete code - run the system for a while through all typical scenarios and collect statistics on loaded classes, invoked methods, etc. Of course report generated using this technique can be only considered as a hint and manual verification is required. Proper solution should probably be done using AOP, instrumenting code either during compile or load time. There is however quick and dirty way that archives similar results.
- Run your app with -verbose:class option (send standard output to file in addition to console using | tee <filename>)
Example:
$ export MAVEN_OPTS="$MAVEN_OPTS -verbose:class" $ mvn clean jetty:run | tee jetty.log
- Execute all typical scenarios of your application
- From generated log file create sorted list of your project classes used in executed scenarios:
$ grep "\[Loaded.*com.jpragma" jetty.log | awk '{print $2}' | sort | uniq -u > loaded_classes.txt
- Create sorted list of your compiled project classes:
$ find target/classes/ -name *.class | sed 's/target\/classes\/\///g' \ | sed 's/.class//g' | tr -s '/' '.' \ | sort > declared_classes.txt
- Compare two txt files finding all classes that declared but not used:
$ diff loaded_classes.txt declared_classes.txt | grep ">"