动态代理的概述和实现
- A:动态代理概述
-
代理:本来应该自己做的事情,请了别人来做,被请的人就是代理对象。
-
举例:春节回家买票让人代买
-
动态代理:在程序运行过程中产生的这个对象,而程序运行过程中产生对象其实就是我们刚才反射讲解的内容,所以,动态代理其实就是通过反射来生成一个代理
-
在Java中java.lang.reflect包下提供了一个Proxy类和一个InvocationHandler接口,通过使用这个类和接口就可以生成动态代理对象。JDK提供的代理只能针对接口做代理。我们有更强大的代理cglib,Proxy类中的方法创建动态代理类对象
-
public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)
-
最终会调用InvocationHandler的方法
-
InvocationHandler Object invoke(Object proxy,Method method,Object[] args)
-
package com.heima.proxy;
public interface User {
public void add();
public void delete();
}
========================================================
package com.heima.proxy;
public class UserImpl implements User {
@Override
public void add() {
// System.out.println("权限校验");
System.out.println("添加功能");
// System.out.println("日志记录");
}
@Override
public void delete() {
// System.out.println("权限校验");
System.out.println("删除功能");
// System.out.println("日志记录");
}
}
========================================================
package com.heima.proxy;
public interface Student {
public void login();
public void submit();
}
========================================================
package com.heima.proxy;
public class StudentImp implements Student {
@Override
public void login() {
System.out.println("登录");
}
@Override
public void submit() {
System.out.println("提交");
}
}
========================================================
package com.heima.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("权限校验");
method.invoke(target, args); //执行被代理target对象的方法
System.out.println("日志记录");
return null;
}
}
========================================================
package com.heima.proxy;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
/*UserImp ui = new UserImp();
ui.add();
ui.delete();
System.out.println("-------------------------------");*/
/*
* public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,
* InvocationHandler h)
*/
/*MyInvocationHandler m = new MyInvocationHandler(ui);
User u = (User)Proxy.newProxyInstance(ui.getClass().getClassLoader(), ui.getClass().getInterfaces(), m);
u.add();
u.delete();*/
StudentImp si = new StudentImp();
si.login();
si.submit();
System.out.println("-------------------------------");
MyInvocationHandler m = new MyInvocationHandler(si);
Student s = (Student)Proxy.newProxyInstance(si.getClass().getClassLoader(), si.getClass().getInterfaces(), m);
s.login();
s.submit();
}
}