代码如下:
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);
result = method.invoke(delegate, args);
System.out.println("方法结束:" + method);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
复制代码代码如下:
public interface Animal {
public void hello();
}
动态代理作为代理模式的一种扩展形式,广泛应用于框架(尤其是基于AOP的框架)的设计与开发,本文将通过实例来讲解Java动态代理的实现过程。
复制代码代码如下:
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();
}
}