package com.free.testProxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 动态代理的三个条件 * 1.有接口 * 2.被代理类实现了该接口 * 3.创建代理类 * */ public class ProxyConnection { private Connection connection; public Connection Getproxy() { Connection connection = (Connection)Proxy.newProxyInstance(jdbcConnection.class.getClassLoader(),jdbcConnection.class.getInterfaces(),new InvocationHandler() { //只要调用代理类的方法都会经过该方法,aop思想 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated mehod stub System.out.println("1"); //调用被代理类自己的方法 System.out.println(proxy.getClass()+""+method.getDeclaringClass()+method.invoke(jdbcConnection.class.newInstance(), args)); // method.invoke(proxy, args); //执行代理类方法之后的操作 System.out.println("2"); return null; } }); return connection; } public static void main(String[] args) { Connection connection2 = new ProxyConnection().Getproxy(); connection2.close(); } }
时间: 2024-11-05 16:30:51