Java中调用一个方法前触发事件,先去调用另外一个方法,怎么写
时间: 2024-01-25 15:03:46 浏览: 26
在Java中,可以使用代理模式来实现在调用一个方法前触发事件并先调用另外一个方法。具体实现步骤如下:
1.创建一个接口,定义要代理的方法和触发事件的方法。
```
public interface ProxyInterface {
void targetMethod();
void beforeMethod();
}
```
2.创建一个实现接口的类,实现接口中定义的方法。
```
public class ProxyImpl implements ProxyInterface {
@Override
public void targetMethod() {
System.out.println("目标方法被调用了");
}
@Override
public void beforeMethod() {
System.out.println("在调用目标方法前触发的方法");
}
}
```
3.创建一个代理类,实现接口中的方法,并在调用目标方法前触发beforeMethod方法。
```
public class Proxy implements ProxyInterface {
private ProxyInterface target;
public Proxy(ProxyInterface target) {
this.target = target;
}
@Override
public void targetMethod() {
beforeMethod();
target.targetMethod();
}
@Override
public void beforeMethod() {
System.out.println("代理对象:在调用目标方法前触发的方法");
}
}
```
4.测试代码:
```
public static void main(String[] args) {
ProxyInterface target = new ProxyImpl();
ProxyInterface proxy = new Proxy(target);
proxy.targetMethod();
}
```
运行结果:
```
代理对象:在调用目标方法前触发的方法
目标方法被调用了
```