如何按实例计算方法调用

Kap*_*pil 1 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以看到我打eat()三次电话.如何计算它被调用的次数?

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

Kar*_*cki 11

您可以将Decorator PatternAnimal接口和您的Lion实例一起使用:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后应用它

Animal lion = new EatingDecorator(new Lion());
lion.eat();
lion.eat();
lion.eat();
System.out.println(((EatingDecorator) lion).getCounter()); // 3
Run Code Online (Sandbox Code Playgroud)

  • 为了让这个例子更加清晰,我将"EatingDecorator lion"改为"Animal lion".否则,人们可能会认为实施"动物"可能没有必要. (2认同)

Ton*_*hen 5

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

代码如下:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

cglib依赖性

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.2.10</version>
    </dependency>
Run Code Online (Sandbox Code Playgroud)