How to Count Method Calls by Instance

How to count method calls by instance

You could use Decorator Pattern with Animal interface and your Lion instance:

public class EatingDecorator implements Animal {
private Animal target;
private int counter;

public EatingDecorator(Animal target) {
this.target = target;
}

@Override
public void eat() {
target.eat();
counter++;
}

public int getCounter() {
return counter;
}
}

and then apply it

Animal lion = new EatingDecorator(new Lion());
lion.eat();
lion.eat();
lion.eat();
System.out.println(((EatingDecorator) lion).getCounter()); // 3

How to count method calls, but not attribute access?

A (python3) solution using a custom metaclass:

from collections import defaultdict
from functools import wraps
import inspect

def count_calls(func):
name = func.__name__

@wraps(func)
def wrapper(self, *args, **kwargs):
# creates the instance counter if necessary
counter = getattr(self, "_calls_counter", None)
if counter is None:
counter = self._calls_counter = defaultdict(int)
counter[name] += 1
return func(self, *args, **kwargs)

wrapper._is_count_call_wrapper = True
return wrapper


class CallCounterType(type):
def __new__(cls, name, bases, attrs):
for name, attr in attrs.items():
if not inspect.isfunction(attr):
# this will weed out any callable that is not truly a function
# (including nested classes, classmethods and staticmethods)
continue

try:
argspec = inspect.getargspec(attr)
except TypeError:
# "unsupported callable" - can't think of any callable
# that might have made it's way until this point and not
# be supported by getargspec but well...
continue

if not argspec.args:
# no argument so it can't be an instancemethod
# (to be exact: a function designed to be used as instancemethod)
# Here again I wonder which function could be found here that
# doesn't take at least `self` but anyway...
continue

if getattr(attr, "_is_count_call_wrapper", False):
# not sure why we would have an already wrapped func here but etc...
continue

# ok, it's a proper function, it takes at least one positional arg,
# and it's not already been wrapped, we should be safe
attrs[name] = count_calls(attr)

return super(CallCounterType, cls).__new__(cls, name, bases, attrs)


class ParentClass(metaclass=CallCounterType):
pass

class ChildClass(ParentClass):
def child_method(self):
pass

Note that storing call counts on the instance only allow to count instancemethods calls, obviously...

How can I count the invocations of a method?

You could use a map to hold the method name and the number of invocations of that method.

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import java.util.Map;

public class InterceptorsBean {

private Map<String, Integer> numberOfInvocations;

@AroundInvoke
public Object methodInterceptors (InvocationContext ctx) throws Exception {
int invocations = 1;

if(numberOfInvocations.containsKey(ctx.getMethod().getName())) {
invocations = numberOfInvocations.get(ctx.getMethod().getName()) + 1;
}

numberOfInvocations.put(ctx.getMethod().getName(), invocations);

System.out.println("Method invocated: " + ctx.getMethod().getName());
System.out.println("Number of invocations: " + invocations);
return ctx.proceed();
}

}

How do i get my program to count the number of times a method is called?

Couldn't you just make a global variable like counter outside of the methods?
Sort of like this.

public class testThingy {
public static int counter = 0;
/* main method and other methods here */
}

Just add 1 to counter every time the method is called (within the method you want counted) and it should update the global variable.

Count method invocation of method variable instance

If possible; I suggest to avoid using mocking libraries that temper with static fields (in the way PowerMock/Mockito do) - as it often comes with undesired side effects (for example many "coverage" tools produce invalid results when static mocking takes places).

So my suggestion: re-design your class under test. Instead of fetching f from a static factory; provide a constructor for either the factory or f; then you can mock the corresponding object; without the need to turn to the mighty but dangerous "Powerxyz" stuff.

Count number of times a method is called?

instances = 0;
instances++;

instances will always equal 1.

What you need to do is make instances a static variable.

public class Circle
{
public static int instances = 0;
}

then inside your constructor class

instances ++;

(Java) Counting recursive calls of method (but always a new instance)

count must be a class variable. You can declare a class variable by using the keyword static :

private static int count = 0;

Count how often static method is called in Java

You're going to want to create a static variable outside of the static method:

private static int counter = 0;

When the method is called, increment the variable:

public static void showObject(Object o){
System.out.println(counter + ": " + o);
counter++;
}


Related Topics



Leave a reply



Submit