Call a method any time other methods are called

后端 未结 5 502
傲寒
傲寒 2021-01-04 11:19

Is there any way to make a sort of \"supermethod\" that is called every time a method is called, even for non-defined methods? Sort of like this:

public void         


        
5条回答
  •  情书的邮戳
    2021-01-04 11:51

    Sure you can do this, not with standard java but with AspectJ

    Here is a simple example:

    Aspect with an after-advice

    package net.fsa.aspectj.test;
    
    
    public aspect SuperMethdAspect {
    
        pointcut afterPointCut() : execution(public * com.my.pack.age.MyClass.*(..));
    
        after() : afterPointCut() {
            System.out.println("Super");
        }
    }
    

    You target class

    package com.my.pack.age;
    
    public class MyClass {
    
        public void onStart() {
            System.out.println("Start");
        }
    
        public void onEnd() {
            System.out.println("End");
        }
    }
    

    And finally some test app

    package net.fsa.aspectj.test;
    
    import com.my.pack.age.MyClass;
    
    public class MyApp {
    
        public static void main(String... args) {
            MyClass myClass = new MyClass();
            myClass.onStart();
            myClass.onEnd();
        }
    }
    

    Output

    Start
    Super
    End
    Super
    

提交回复
热议问题