基於子類的動態代理:如果是maven工程則需先引入依賴
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>
提供方:第三方cglib庫
創建代理類的要求: 被代理類不能是final類
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
/**
* create方法的參數
* class:字節碼
* 它是用於指定被代理對象字節碼的
*
* callback:提供增強的代碼
* 它是讓我們寫如何代理。我們一般都是寫一個該接口的實現類,通常情況下都是匿名內部類,但不是必須的
*
* 我們一般寫的是該接口的子接口實現類,MethodIntercepter
*
*/
Producer producerCglib =(Producer) Enhancer.create(producer.getClass(),
new MethodInterceptor() {
/**
*
* @param o
* @param method
* @param objects
* 以上三個參數和基於接口的動態代理中invoke方法的參數是一樣的
* @param methodProxy:當前執行方法的代理對象
* @return
* @throws Throwable
*/
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//提供增強的代碼
Object returnValue = null;
//獲取方法執行的參數
Float money = (Float) objects[0];
//判斷當前方法是不是銷售
if ("saleProduct".equals(method.getName())) {
returnValue = method.invoke(producer, money * 0.8f);
}
return returnValue;
//return method.invoke(producer,args);
}
});
producerCglib.saleProduct(10000f);
}
}