Java动态代理

主要使用了java.lang.reflect中的Proxy类,

方法如下:

static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) 

下面是利用JDBC做的测试,类似于重写了Connection的close方法。代码如下:

package com.victor_03;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;

import org.junit.Test;

public class MyPool {
    private String url = "jdbc:mysql://192.168.244.144:3306/test";
    private String user = "root";
    private String password = "123456";

    @Test
    public void ProxyTest() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        final Connection conn = DriverManager.getConnection(url, user, password);
        Connection proxy = (Connection) Proxy.newProxyInstance(
                            conn.getClass().getClassLoader(), //类加载器
                         //目标对象实现的接口,因该Connection本来就是个结果,故使用这种方法,如果目标对象本身是类,则使用方式为:conn.getClass().getInterfaces()
                            new Class[] { Connection.class }, 
                            new InvocationHandler() { //当调用conn对象方法时,自动触发事务处理器

                    @Override
                    public Object invoke(Object proxy, Method method,
                            Object[] args) throws Throwable {

                        Object result = null;
                        String methodName = method.getName();
                        if ("close".equals(methodName)) {
                            System.out.println("开始执行close方法");
                        } else {
                            result = method.invoke(conn, args);
                        }
                        return result;
                    }
                });
        proxy.close();
    }
}
原文地址:https://www.cnblogs.com/ivictor/p/5072462.html