How to use IntelliJ IDEA to find all unused code?

JavaRefactoringIntellij IdeaCode MetricsCode Inspection

Java Problem Overview


When I am in a .java file the unused code is usually grayed out or has a green underline saying this code will probably (probably because of some weird JNI/Reflection corner cases) be unused. But I have this project with thousands of Java files and I want to find ALL INSTANCES of such probable-unused codes. How can I do that in IntelliJ IDEA?

Java Solutions


Solution 1 - Java

Just use Analyze | Inspect Code with appropriate inspection enabled (Unused declaration under Declaration redundancy group).

Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"

Solution 2 - Java

In newer versions of IntelliJ it's under Code -> Analyze Code -> Run Inspection by Name.

In IntelliJ versions before that, you should run it from Analyze -> Run Inspection By Name:

enter image description here

Than, pick Unused declaration:

enter image description here

And finally, uncheck the Include test sources:

enter image description here

Solution 3 - Java

After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.

Don't forget to hit Do Refactor afterwards.

Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.

Apply quick fixes to all the problems

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpathikritView Question on Stackoverflow
Solution 1 - JavaCrazyCoderView Answer on Stackoverflow
Solution 2 - JavaJohnnyView Answer on Stackoverflow
Solution 3 - JavaOrwellophileView Answer on Stackoverflow