- 動態代理:
- 特點:字節碼隨用隨創建,隨用隨加載
- 作用:不修改源碼的基礎上對方法增強
- 分類:
1. 使用 JDK 官方的 Proxy 類創建代理對象
- 基於接口的動態代理
- 如何創建代理對象:
- 使用Proxy類中的newProxyInstance方法
- 創建代理對象的要求:
- newProxyInstance方法的參數:
- ClassLoader:類加載器
- 它是用於加載代理對象字節碼的。和被代理對象使用相同的類加載器。固定寫法
- Class[]:字節碼數組
- InvocationHandler:用於提供增強的代碼
- 它是讓我們寫如何代理。我們一般都是寫一個該接口的實現類,通常情況下都是匿名內部類,但不是必須的。
- 此接口的實現類都是誰用誰寫。
package com.siyi.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
IProducer proxyProducer = (IProducer)Proxy.newProxyInstance(producer.getClass().getClassLoader(),
producer.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnValue=null;
Float money = (Float)args[0];
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
});
proxyProducer.saleProduct(10000f);
}
}
2. 使用 cglib 的 Enhancer 類創建代理對象
- 基於子類的動態代理
- 涉及的類:Enhancer
- 提供者:第三方cglib庫
- 如何創建代理對象:
- 創建代理對象的要求:
- create方法的參數:
- Class:字節碼
- Callback:用於提供增強的代碼
- 它是讓我們寫如何代理。我們一般都是寫一個該接口的實現類,通常情況下都是匿名內部類,但不是必須的。
- 此接口的實現類都是誰用誰寫。
- 我們一般寫的都是該接口的子接口實現類:MethodInterceptor
package com.siyi.cglib;
import com.siyi.proxy.IProducer;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
Producer cglibProdicer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
Object returnValue=null;
Float money = (Float)args[0];
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
});
cglibProdicer.saleProduct(12000f);
}
}