JPragma Blog

Pragmatic Developers, Elegant Software

Finding unused code in Java projects

with one comment

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 ">"
Advertisements

Written by isaaclevin

February 14, 2010 at 7:24 pm

Posted in Java

One Response

Subscribe to comments with RSS.

  1. Hi Isaaclevin,

    UCDetector is a eclipse plugin, which can also find unused code in Java projects.

    Joerg

    Joerg

    March 5, 2011 at 12:57 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: