Can findbugs detect unused public methods

后端 未结 8 1616
死守一世寂寞
死守一世寂寞 2020-12-19 04:45

Is it possible to detect unused methods in a source tree using FindBugs? I see some posts on SO where users are claiming to do that, some others asking how to do this in FB

相关标签:
8条回答
  • 2020-12-19 05:14

    Well, as of findbugs-1.3.9, it appears it does not catch unused methods.

    When I ran findbugs on this small sample:

    public class TestJava
    {
     int j;
     public static void main(String[] args)
     { 
       System.out.println("Nothing.");
     }
     public void foo()
     {
     }
     public static void bar()
     {
     }
    }
    

    It did not catch that neither foo nor bar are unused. It did catch that TestJava.j is an unused field.

    Unused field
    This field is never used.  Consider removing it from the class.
    

    findbugs is far from perfect, but it's still a pretty useful tool.

    0 讨论(0)
  • 2020-12-19 05:18

    I suppose it would be quite possible for Findbugs to report on public methods which are not used the same way it reports on privates (either that or I'm thinking of a compiler flag :-).

    The real question is why would you want too? If you are writing a program which is closed and will never be extended, then locating unused methods gives you an opportunity to remove them. But if you are writing an API you cannot predict who will need those methods so there is not much point in reporting on them.

    0 讨论(0)
  • 2020-12-19 05:20

    Maybe crap4j is what you need. It removes all code that is not reached by unit tests. This is of course the hard way to minimize your app.

    0 讨论(0)
  • 2020-12-19 05:22

    I have a project i'm currently working on that does just this.... It's very early on tho, so probably a bunch of bugs left:

    https://github.com/mebigfatguy/deadmethods

    0 讨论(0)
  • 2020-12-19 05:24

    Well, since you want to go down this route despite warnings from the others who've responded :), you can copy and modify the UPM detector to do what you need.

    Its really simple to write a detector for FindBugs (especially when you've got a great starting point). Read this to get you started

    0 讨论(0)
  • 2020-12-19 05:28

    Removing unused code (including unused public methods) is one thing obfuscators do. The problem is that you can't really tell if a public method is used by just looking at the class that contains it. You need to look at the whole system that is going to run, because a public method might be called from everywhere.

    Running the obfuscator against the whole system (i.e. your code and all libraries used to run the system) can help find public methods that are never called (caveat: reflection can mess with that result, of course!).

    0 讨论(0)
提交回复
热议问题