Call a method any time other methods are called

后端 未结 5 458
傲寒
傲寒 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:57

    Here is an implementation in pure Java using the Proxy class:

    import java.lang.reflect.*;
    import java.util.*;
    
    public class Demo
    {
        public static void main(String[] args)
        {
            Map map = new HashMap();
            map.put("onStart", "abc");
            map.put("onEnd", "def");
            Library library = new LibraryProxy(map, new LibraryImpl()).proxy();
            library.onStart();
            library.onEnd();
            library.onRun();
        }
    }
    
    interface Library
    {
        void onStart();
        void onEnd();
        void onRun();
    }
    
    class LibraryImpl
    {
        public void abc() { System.out.println("Start"); }
        public void def() { System.out.println("End"); }
    }
    
    class LibraryProxy implements InvocationHandler
    {
        Map map;
        Object impl;
    
        public LibraryProxy(Map map, Object impl)
        {
            this.map = map;
            this.impl = impl;
        }
    
        public Library proxy()
        {
            return (Library) Proxy.newProxyInstance(Library.class.getClassLoader(),
                new Class[] { Library.class }, this);
        }
    
        @Override
        public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
        {
            Object res = null;
            String name = map.get(m.getName());
            if (name == null) {
                System.out.println("[" + m.getName() + " is not defined]");
            } else {
                m = impl.getClass().getMethod(name, m.getParameterTypes());
                res = m.invoke(impl, args);
            }
            System.out.println("super duper");
            return res;
        }
    }
    

    Output:

    Start
    super duper
    End
    super duper
    [onRun is not defined]
    super duper
    

提交回复
热议问题