jdk动态代理实例

实现动态代理的步骤:
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);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章