hoipolloi
hoipolloi

Reputation: 8044

Finding unused code in Java with AspectJ

I have an idea for finding unused ('dead') methods in a large Java project but I need help deriving an implementation.

  1. Use AspectJ to add a 'before' aspect to ALL methods in project packages. The aspect will simply record (?) that the method has been executed.
  2. I compile a list of all classes/methods in project packages (probably using a service locator/reflection).
  3. The advised code is subjected to a full regression test. Ideally, I'd like to put this into production for a while too (if a suitably performant solution can be found).
  4. The lists of executed methods (Step 1) and available methods (Step 2) are compared, yielding a comprehensive list of all methods that were never called (i.e. dead code).

Since steps 2 and 4 can be conducted offline, I'm really only looking for help with Step 1.

Specifically, how can I record when a method is executed? I figure I'm going to encounter OutOfMemoryErrors pretty soon if I attempt any kind of in-memory storage. Likewise, if I store the data in a database/on the file-system, the volume of calls is likely to cause major performance issues. Has anyone ever done something similar? Any advice/suggestions appreciated.

Upvotes: 2

Views: 700

Answers (2)

Sled
Sled

Reputation: 18959

Well you want a before call advice. On that advice you'd want to log the method being called. Probably you'd want to keep a set of the methods called so that you don't get duplicates. You could get the current method off of the thisJointPoint. I could give the AspectJ code for it but I think it's beside the point.

I think you'd be better off just using a tool to parse the binary .class files using BECL or ASM, starting with methods you know get called, and build a call graph. This is similar to how the JVM does garbage collection.

But, really you should ask yourself for what you are this. Is it performance? Because the impact should be none. If you want to reduce the size of the .class files you'd be better off using something like ProGuard. That will take care of that and other issues and its already made.

That said I think the best approach if you really want to do this is to instrument your code using Cobertura, and do a run-through of your application and then look at your coverage reports. It shouldn't take long for 90% of your used code to be painted. Any uncalled methods that you can delete without causing a compile error are dead code.

Upvotes: 0

Ryan Stewart
Ryan Stewart

Reputation: 128899

Try checking out popular test coverage libraries like Cobertura or EMMA. They do exactly what you're talking about and then some, though not with AspectJ. Cobertura, at least, seems to have no problem storing invocation information down to the line in memory.

Upvotes: 1

Related Questions