接口类UserDao:
package com.ant.jdk8.proxy;public interface UserDao { void save();}
接口类EmployeeDao:
package com.ant.jdk8.proxy;public interface EmployeeDao { void add();}
目标类UserDaoImpl:
package com.ant.jdk8.proxy;public class UserDaoImpl implements UserDao { @Override public void save() { System.out.println("保存用户"); }}
目标类EmployeeDaoImpl:
package com.ant.jdk8.proxy;public class EmployeeDaoImpl implements EmployeeDao { @Override public void add() { System.out.println("添加雇员信息"); }}
代理类ProxyFactory:
package com.ant.jdk8.proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class ProxyFactory { //维护一个目标对象 private Object target; public ProxyFactory(Object target){ this.target = target; } //生成目标对象的代理对象 public Object getProxyInstance(){ return Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler(){ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("---开始事务---"); Object object = method.invoke(target, args); System.out.println("---提交事务---"); return object; } }); }}
测试类APP:
package com.ant.jdk8.proxy;public class App { public static void main(String[] args) { //目标对象 UserDao target = new UserDaoImpl(); //代理对象 UserDao proxy = (UserDao) new ProxyFactory(target).getProxyInstance(); proxy.save(); System.out.println("=========================="); //目标对象 EmployeeDao target2 = new EmployeeDaoImpl(); //代理对象 EmployeeDao proxy2 = (EmployeeDao)new ProxyFactory(target2).getProxyInstance(); proxy2.add(); }}
JDK动态代理总结:
代理对象不需要实现接口,但是目标对象一定要实现接口,否则不能用动态代理。