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.

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.

  1. 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
  2. Execute all typical scenarios of your application
  3. 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
  4. 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
  5. Compare two txt files finding all classes that declared but not used: $ diff loaded_classes.txt declared_classes.txt | grep ">"
Written on February 14, 2010