java动态代理 java实现动态代理示例分享
人气:0import 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();
}
}
加载全部内容