How to count method calls by instance

  • A+

I have following Code.

public interface Animal{      void eat(); }  public class Lion implements Animal{      @Override     public void eat() {         System.out.println("Lion can eat");     }     public static void main(String[] args) {          Animal lion = new Lion();;;;     } } 

as you can see I am calling eat() thrice. How can I calculate how many times it is called?

Note that, you can not modify eat() method from class Lion


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) { = target;   }    @Override   public void eat() {;     counter++;   }    public int getCounter() {     return counter;   } } 

and then apply it

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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: