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

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

问题描述

像这样:一类有一个叫做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.

样品code可以是这样的:

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

然后把方法的sayHello的MethodListener注释()在Person类,

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.

由机器人法的人法的装修在施工Person实例的过程中发生的,但是你需要使用AOP的容器,而不是提供了一个工厂类

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天全站免登陆