How to count method calls by instance

  • A+
Category:Languages

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();         lion.eat();         lion.eat();         lion.eat();     } } 

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) {     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 

Comment

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