Java动态代理

本文介绍如何使用Java的动态代理技术实现对JDBC Connection接口的增强,通过重写Connection的close方法来演示代理模式的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要使用了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();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值