如何按实例计算方法调用

时间:2019-01-18 13:23:39

标签: java oop

我有以下代码。

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

您可以看到我三次打eat()。我该如何计算它被调用多少次?

请注意, 您无法修改类eat()中的Lion方法

3 个答案:

答案 0 :(得分:11)

您可以通过Animal界面和Lion实例使用Decorator Pattern

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;
  }
}

然后应用

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

答案 1 :(得分:4)

使用代理可以提供帮助,在许多情况下,我们无法修改代码,但是我们可以创建代理并执行您想要的操作。

代码如下:

public class Lion implements Animal {
    @Override
    public void eat() {
        System.out.println("Lion can eat");
    }
public static AtomicInteger counts = new AtomicInteger(0);
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Lion.class);
        enhancer.setCallback((MethodInterceptor) (obj, method, args1, proxy) -> {
            counts.getAndIncrement();
            return proxy.invokeSuper(obj, args1);
        });
        Animal lion = (Lion) enhancer.create();
        lion.eat();
        lion.eat();
        lion.eat();

        System.out.println("method called " + counts.get() + " times");
    }
}

cglib依赖

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.2.10</version>
    </dependency>

答案 2 :(得分:-1)

您可以使用Mockito制作一个测试单元-运行测试并使用以下代码实现:

Mockito.verify(mock,times(4))。send();