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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值