开发者

How to know, the number of times a particular method is invoked in java

Is there any way to know how many times a instance of a class has invoked its member method.

I think(not sure), one way is to have a dedicated a member variable for a method, But that will not be feasible if we have so many methods.

Fo开发者_开发问答r example:

class A{
        public void someMethod(){   
        }
}

and i have a instance say

A a = new A();

So I want to know the Number of times a has invoked someMethod in a program. We can have any number of methods.


If you need this information inside the program, this is exactly what aspect oriented programming is meant for. Using AspectJ, it would be quite easy. Spring AOP will probably also work.


Indeed, AOP would be the right tool here and I would write a little aspect to use JAMon (which can precisely gather statistics such as hits, time statistics (avg,total,min,max), concurrency statistics and more). See this previous answer for an example (or goolge a bit). If you are using Spring, then Spring has a ready to use JamonPerformanceMonitorInterceptor.


There are a few approaches you could take, depending on how easily you can modify the code:

  • just add the counter variable as you suggest; clumsy if you have to add it in a lot of places, but easy to code
  • put your counter code in some other utility class, with a single method that you call from all relevant places to "increment counter for this method"; the utility method in question then examines the call stack-- e.g. via (new Exception()).getStackTrace()-- to see who was calling and increment the relevant counter
  • use a profiler that provides this facility
  • use the ASM library to add a counter.
  • use the Java instrumentation framework to modify the class definitions of relevant methods on the fly as the classes are loaded; this is potentially the most flexible-- you can even instrument code that you haven't actually written yourself and can't modify, and it means you don't have to alter the code of the actual classes you want to perform counting on-- but it is by far the most complex to code.


You may consider using profilers, e.g. one from NetBeans or YourKit, etc.


There a lot of Open Source Java Profilers.

A profiler does dynamic program analysis (as opposed to static code analysis), and shows a program's behavior, gathering information as the program executes. Some of these profilers shows method invocation statistics.


If you have access to JProbe it will tell you the number of times a method was invoked by a particular instance.

They say MAT is also good and its free, I haven't tried it yet.


It's possible to do with java.lang.reflect.Proxy class. In Horstmann's book 'Core Java. Volume I' this technique is described in details.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜