jdk动态代理小例子

jdk动态代理:

        需要:接口;接口实现类;InvocationHandler实现类;测试类

代理要求:要求被代理的对象实现了一个接口;

代理:InvocationHandler实现类中重写的invoke方法;就是生成的代理对象实际执行的方法;其中Method就是明星接口的方法;

在测试类中使用Proxy生成代理对象;

方法入参有:被代理类的类加载器;被代理类的接口信息;和被代理类的InvocationHandler实现类;

明星接口实现类

import aop.inter.MingXing;

public class Mingxingimpl implements MingXing {
    @Override
    public void dosome() {
        System.out.println("大家好!我是大明星");
    }

    @Override
    public void doother() {
        System.out.println("大家好记得给钱");
    }
}

 明星代理类

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MingxingDaili implements InvocationHandler {


    private Object target;

    public MingxingDaili() {
    }

    public MingxingDaili(Object target){
        this.target=target;//将被代理的对象
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object res=null;
        System.out.println("经纪人商谈");
        res=method.invoke(target,args);
        System.out.println("结算费用");
        return res;
    }
}

 明星接口

public interface MingXing {
    void dosome();
    void doother();
}

 动态代理测试类

import aop.entity.Mingxingimpl;
import aop.hander.MingxingDaili;
import aop.inter.MingXing;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class test001 {
    public static void main(String[] args) {
        MingXing mingXing=new Mingxingimpl();
        InvocationHandler invo=new MingxingDaili(mingXing);
        MingXing proxy= (MingXing) Proxy.newProxyInstance(
                        mingXing.getClass().getClassLoader(),//被代理类的类加载器
                        mingXing.getClass().getInterfaces(),//被代理类实现的接口
                        invo);//被代理类的invocation包装类
        proxy.dosome();
        proxy.doother();
    }
}

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏与ta

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值