像这样:一个类有一个名为sayHello()的方法。当类的一个实例调用sayHello()时,另一个类中的方法在调用sayHello()之前被称为自动。如何在调用方法之前将方法称为被动方法
样本代码可以是这样的:
public class Robot{
public static void doSomethingBefore(){
System.out.println("Do something before sayHello");
}
}
public class Person {
public void sayHello(){
System.out.println("hello");
}
public static void main(String[] args){
Person p = new Person();
p.sayHello();
}
}
输出结果:
Do something before sayHello
hello
现在看来,这可以通过使用代理模式来完成。但我希望它可以更简单。
使用注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MethodListener {
public String className();
public String methodName();
}
然后把MethodListener标注在Person类方法的sayHello(),
public class Person {
@MethodListener(className="Robot",methodName="doSomethingBefore")
public void sayHello(){
System.out.println("hello");
}
public static void main(String[] args){
Person p = new Person();
p.sayHello();
}
}
当它具有MethodListener注解的方法被调用,方法doSomethingBefore()被称为自动。
应该有可能吗?如果可以做到,如何实现呢?