Java implements dynamic proxy sample sharing

  • 2020-04-01 03:06:37
  • OfStack


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class LogHandler implements InvocationHandler {
    private Object delegate;
    public Object bind(Object delegate) {
        this.delegate = delegate;
        return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
                delegate.getClass().getInterfaces(), this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Object result = null;
        try {
            System.out.println(" Method start: " + method);
            result = method.invoke(delegate, args);
            System.out.println(" Method end: " + method);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}


public interface Animal {
    public void hello();
}

As an extension of the proxy pattern, dynamic proxy is widely used in the design and development of frameworks (especially aop-based frameworks). This article will explain the implementation process of Java dynamic proxy through examples.


public class Monkey implements Animal {
    @Override
    public void hello() {
        // TODO Auto-generated method stub
        System.out.println("hello");
    }
}


public class Main {
    public static void main(String[] args) {
        LogHandler logHandler = new LogHandler();
        Animal animal = (Animal) logHandler.bind(new Monkey());
        animal.hello();
    }
}


< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201403/20140321150936.jpg? 2014221151043 ">


Related articles: