主要分为两种 jdk代理和cglib开源库代理
jdk代理主要针对接口,实现InvocationHandler。
cglib主要通过框架修改字节码,创建出代理类的子类实现代理, 对于final类不适用. 实现methodInterceptor接口. cglib包-github
jdk代理 代码demo:
public interface ProxyInterface { //接口
public void sayHello();
}
public class ProxyHandler implements InvocationHandler {
private Object object; //代理类 可以结合工厂用
public ProxyHandler() {
}
public ProxyHandler(Object object) {
this.object = object;
}
//第一个参数 proxy 至今不知道作用
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//AOP的核心机制
//before
System.out.println("invoke in before");
method.invoke(this.object,args);
//after
System.out.println("invoke in after");
return null;
}
//获取最新的代理类,利用了多态
public Object getProxy() {
ProxyInterface proxy = (ProxyInterface)Proxy.newProxyInstance(this.getClass().getClassLoader(),
this.object.getClass().getInterfaces(), this);
return proxy;
}
}
public class ProxyClass implements ProxyInterface{ //具体的实现类
public void sayHello() {
System.out.println("say hello in proxy class");
}
public static void main(String[] args) { //主函数
ProxyInterface pi = new ProxyClass();
ProxyInterface proxyClass = (ProxyInterface)new ProxyHandler(pi).getProxy();
proxyClass.sayHello(); //此时打印之后就是 有before和after的方法
}
}