實現動態代理的步驟:
1、創建接口,定義目標類要完成的功能
2、創建目標類實現接口
3、創建invocationHandler接口的實現類,在invoke方法中完成代理類的功能(1)調用目標方法(2)增強功能
4、使用proxy類的靜態方法,創建代理對象。並把返回值轉爲接口類型
下面是一個賣u盤的實例
//接口 定義目標類要完成的方法sell
public interface UsbSell {
float sell(int amount);
}
import com.luna.service.UsbSell;
//目標類
public class KingFactory implements UsbSell {
@Override
public float sell(int amount) {
//目標方法
System.out.println("目標類中 執行sell方法");
return 85.0f;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyHandler implements InvocationHandler {
private Object target=null;
public MyHandler(Object target){
this.target=target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object res=method.invoke(target,args);
if(null!=res){
Float price=(Float)res;
price=price+25;
res=price;
}
return res;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
//使用Proxy創建對象
public class test {
public static void main(String[] args) {
//1 創建目標對象 下面這行等同於 UsbSell usbSell=new KingFactory();
KingFactory factory =new KingFactory();
//2 創建InvocationHandler對象
InvocationHandler handler=new MyHandler(factory);
//3 創建代理對象
UsbSell proxy=(UsbSell)Proxy.newProxyInstance(factory.getClass().getClassLoader(),
factory.getClass().getInterfaces(),
handler);
//4 通過代理執行方法
float price=proxy.sell(1);
System.out.println("通過動態代理對象調用方法"+price);
}
}