动态代理的概述和实现
生活随笔
收集整理的這篇文章主要介紹了
动态代理的概述和实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
動態代理?
代理:
本來應該自己做的事情,卻請了別人來做,被請的人就是代理對象。
舉例:春季回家買票讓人代買
動態代理:
在程序運行過程中產生的這個對象
而程序運行過程中產生對象其實就是我們剛才反射講解的內容,所以,動態代理其實就是通過反射來生成一個代理
在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 cn.learn_06;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;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("權限校驗");Object result = method.invoke(target, args);System.out.println("日志記錄");return result; // 返回的是代理對象} } package cn.learn_06;import java.lang.reflect.Proxy;public class Test {public static void main(String[] args) {UserDao ud = new UserDaoImpl();ud.add();ud.delete();ud.update();ud.find();System.out.println("-----------");// 我們要創建一個動態代理對象// Proxy類中有一個方法可以創建動態代理對象// public static Object newProxyInstance(ClassLoader loader,Class<?>[]// interfaces,InvocationHandler h)// 我準備對ud對象做一個代理對象MyInvocationHandler handler = new MyInvocationHandler(ud);UserDao proxy = (UserDao) Proxy.newProxyInstance(ud.getClass().getClassLoader(), ud.getClass().getInterfaces(), handler);proxy.add();proxy.delete();proxy.update();proxy.find();System.out.println("-----------");StudentDao sd = new StudentDaoImpl();MyInvocationHandler handler2 = new MyInvocationHandler(sd);StudentDao proxy2 = (StudentDao) Proxy.newProxyInstance(sd.getClass().getClassLoader(), sd.getClass().getInterfaces(), handler2);proxy2.login();proxy2.regist();} }?
總結
以上是生活随笔為你收集整理的动态代理的概述和实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通过反射写一个通用的设置某个对象的某个属
- 下一篇: 装饰模式概述和使用