The code copy is as follows:
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;
}
}
The code copy is as follows:
public interface Animal {
public void hello();
}
Dynamic proxy is an extended form of the proxy model and 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.
The code copy is as follows:
public class Monkey implements Animal {
@Override
public void hello() {
// TODO Auto-generated method stub
System.out.println("hello");
}
}
The code copy is as follows:
public class Main {
public static void main(String[] args) {
LogHandler logHandler = new LogHandler();
Animal animal = (Animal) logHandler.bind(new Monkey());
animal.hello();
}
}