在大型java项目中,您使用什么工具来查找未使用的/死亡的代码?我们的产品已经开发了几年,手动检测不再使用的代码变得非常困难。但是,我们会尽量删除未使用的代码。

对于一般策略/技术(而不是特定工具)的建议也很感激。

编辑:请注意,我们已经使用了代码覆盖工具(Clover, IntelliJ),但这些帮助不大。死代码仍然有单元测试,并显示为已覆盖。我想理想的工具应该是识别那些依赖于它的其他代码很少的代码集群,从而允许手动检查文档。


当前回答

我使用Doxygen开发了一个方法调用映射来定位从未调用过的方法。在图中,您将发现没有调用者的方法集群孤岛。这对库不起作用,因为您总是需要从一些主要入口点开始。

其他回答

IntelliJ有代码分析工具,用于检测未使用的代码。你应该试着让尽可能多的字段/方法/类成为非公共的,这样会显示出更多未使用的方法/字段/类

我还会尝试找到重复的代码,作为减少代码量的一种方式。

我的最后一个建议是,尽量找到开放源代码,如果使用,会使您的代码更简单。

FindBugs非常适合做这类事情。 PMD (Project Mess Detector)是另一个可以使用的工具。

但是,两者都不能找到工作区中未使用的公共静态方法。如果有人知道这样的工具,那么请让我知道。

一个工作得相当不错的Eclipse插件是未使用代码检测器。

它处理整个项目或特定文件,并显示各种未使用/死亡的代码方法,以及建议可见性更改(即可以保护或私有的公共方法)。

DCD不是某些IDE的插件,但可以从ant或独立运行。它看起来像一个静态工具,它可以做PMD和FindBugs不能做的事情。我会试试的。

附注:正如下面的评论中提到的,该项目现在存在于GitHub中。

我很惊讶这里竟然没有提到ProGuard。这是目前最成熟的产品之一。

ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods using short meaningless names. Finally, it preverifies the processed code for Java 6 or for Java Micro Edition. Some uses of ProGuard are: Creating more compact code, for smaller code archives, faster transfer across networks, faster loading, and smaller memory footprints. Making programs and libraries harder to reverse-engineer. Listing dead code, so it can be removed from the source code. Retargeting and preverifying existing class files for Java 6 or higher, to take full advantage of their faster class loading.

下面是列表死代码的示例:https://www.guardsquare.com/en/products/proguard/manual/examples#deadcode