反射_动态代理的概述和实现

来源:互联网 发布:linux posix 编辑:程序博客网 时间:2024/05/17 00:56
package cn.itcast_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)// proxy:  指代我们所代理的那个真实对象// method:  指代的是我们所要调用真实对象的某个方法的Method对象// args:  指代的是调用真实对象某个方法时接受的参数// 我准备对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();}}

解惑:

给的接口里面有哪些方法,生成的代理里面就有哪些方法。classs $Proxy4 implments UserDao{save(User u){Method m = UserDao.getClass.getMethod();li.invoke(this,m,u);}}

package cn.itcast_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;// 返回的是代理对象}}



0 0
原创粉丝点击