jdk动态代理
Posted danial7777777
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jdk动态代理相关的知识,希望对你有一定的参考价值。
package proxy.jdk; public interface UserDao { public void add(); public void delete(); }
package proxy.jdk; public class UserDaoimpl implements UserDao{ @Override public void add() { // TODO Auto-generated method stub System.out.println("user add success!"); } @Override public void delete() { // TODO Auto-generated method stub System.out.println("user delete success!"); } }
package proxy.jdk; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Handler implements InvocationHandler{ public Object target; public Handler(Object target) { super(); this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("代理执行前"); Object o = method.invoke(target, args); System.out.println("代理执行后"); return o; } public Object getProxy() { return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this); } }
package proxy.jdk; public class Test { public static void main(String[] args) { UserDao userDao=new UserDaoimpl(); Handler handler=new Handler(userDao); UserDao userProxy = (UserDao) handler.getProxy(); userProxy.add(); userProxy.delete(); } }
以上是关于jdk动态代理的主要内容,如果未能解决你的问题,请参考以下文章