如何在调用方法之前使方法被调用为被动 [英] How to make a method be called passive before invoke a method

查看:31
本文介绍了如何在调用方法之前使方法被调用为被动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样:一个类有一个名为 sayHello() 的方法.当类的实例调用 sayHello() 时,在调用 sayHello() 之前自动调用另一个类中的方法.

Like so : a class has a method called sayHello() . When a instance of the class call the sayHello(), a method in another class is called automatic before the sayHello() is called.

示例代码可以是这样的:

the sample code can be like this:

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

似乎可以通过使用代理模式来完成.但我希望它可以更简单.

It seems it can be done by using the proxy pattern. But I want it can be more simple.

使用注解:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MethodListener {
      public String className();
      public String methodName();
}

然后在Person类的sayHello()方法上加上MethodListener注解,

Then put the MethodListener annotation on the method sayHello() in the Person class,

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()方法被自动调用.

When the method which has the MethodListener annotation be called, the method doSomethingBefore() is called automatic.

应该可以吗?如果可以,如何实现?

Should it be possible ? If it can be done, how to achieve it?

推荐答案

我认为您正在寻找面向方面的编程框架,例如 AspectJ、JBoss AOP 或 Spring AOP.

I think you are looking for an aspect-oriented programming framework such as AspectJ, JBoss AOP or Spring AOP.

Robot 方法对 Person 方法的修饰会在构建 Person 实例的过程中发生,但是您需要使用 AOP 容器提供的工厂类,而不是 new.

The decoration of the Person method by the Robot method will happen during construction of the Person instance, but you will need to use a factory class provided by the AOP container instead of new.

这篇关于如何在调用方法之前使方法被调用为被动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆