黑马程序员————动态代理

动态代理
代理:本来应该自己做的事情,却请了别人来做,被请的人就是代理对象。
举例:春季回家买票让人代买
动态代理:在程序运行过程中产生的这个对象

而程序运行过程中产生对象其实就是我们刚才反射讲解的内容,所以,动态代理其实就是通过反射来生成一个代理

在Java中java.lang.reflect包下提供了一个Proxy类和一个InvocationHandler接口,通过使用这个类和接口就可以生成动态代理对象。JDK提供的代理只能针对接口做代理。我们有更强大的代理cglib

动态代理的实现:

步骤:1.所代理的类,一定要有一个"父接口";
   2.自己定义一个类,实现InvocationHandler接口,并重写:invoke()方法;
        在invoke()方法中,使用Java的反射机制,动态调用所需调用的方法,并增加新的内容;
   3.当需要获取某个类的"代理对象"时:
        调用:Proxy类中的一个静态方法:newProxyInstance()就能获取某个类的代理对象;

public interface IStudent {
public void coding();
}

public class Student implements IStudent {

@Override
public void coding() {
System.out.println("我写代码,我做项目......");
}
}

public class MyHandler implements InvocationHandler {
private Object target;
public MyHandler(Object t){
this.target = t;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
check();
//调用原用户想调用的方法
//使用反射,去调用
Object result = method.invoke(target, args);//当代理Student对象时,method就代表coding()方法
zj();
return result;

}

private void check(){
System.out.println("先期检查......");
}
private void zj(){
System.out.println("后期总结......");
}
}

public class Demo {
public static void main(String[] args) throws Exception {
// 不使用代理
/*
* IStudent stu = new Student(); stu.coding();
*/

// 使用代理
// 以下方法的调用,获取了一个Student类的代理对象;
IStudent stu = (IStudent) Proxy.newProxyInstance(
Student.class.getClassLoader(), Student.class.getInterfaces(),
new MyHandler(new Student()));
stu.coding();


// 为Teacher生成代理类
ITeacher tea = (ITeacher) Proxy.newProxyInstance(
Teacher.class.getClassLoader(), Teacher.class.getInterfaces(),
new MyHandler(new Teacher()));
tea.teach();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值