开发者

How do I determine which methods are used by a Java class

I need to provide a report of which APIs are used by our code, and exactly which methods are called. For a Wind开发者_StackOverflowows DLL, I would use "dumpbin /imports" - is there an equivalent for a Java .class file?

javap seems to be the obvious place to look, but I can't find any options that seem to do what I'm after.


javap -c class1 class2 ... | grep invoke

You will get all the runtime calls. You should filter them from your APIs and you will get calls to imported methods.

You might also want to determine used imported fields:

javap -c class1 class2 ... | grep getstatic (search also putstatic, putfield, getfield)


It's brutal, but you could try something like this:

  1. do a global search/replace in your code for "import x.y.Z" with static class Z{} where package x.y is from your thirdparty

  2. jar run your compile script (or copy the errors from your IDE if possible)

  3. process the compilation errors looking for "The method xxx is undefined" type of messages


How about Apache/Maven jxr?


I don't know a specific tool to do this, but it seems to me it could be done with moderate difficulty using a perl script, if you have the jar or source.

You can run the jar through jad http://en.wikipedia.org/wiki/JAD_(JAva_Decompiler) to generate the source, then write a perl script that:

  1. Scans through each file of your source

    a. finds all import reg expression strings

    b finds all source files in the decompiled third party source that matches the imported package

    c. for each file in the third party, extract the method names

    d. if it matches, save the method + class + package.

This can of course be made much more efficient - you could make an hash table of all packages, and within that, a hash table of all methods for the third party.

Once a method is used, you can delete it from the table since you don't need to look for it again.

But probably the brute force method is sufficient, because this is not a computationally intensive problem (though of course for a human it would be very labor intensive!).

Substitute ruby/python/php/sed/awk for perl if that is your preference.


If you want a lot of power and flexibility, I would definitely take a look at the ASM library

There are basically a lot of great tools for analysing and manipulating java bytecode. One of the ones you may find most useful is a vistor-based API which can walk through the internals of any class and perform any analysis you want (in your case detecting which other classes / packages are referenced).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜