JDK Proxy使用

1: 使用JDK Proxy 进行动态拦截某个类的方法执行, 此类必须实现某个接口.

 

2:例子如下:

package com.toon.mybatis.dao.monitor;

import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

import javax.sql.DataSource;

import com.jamonapi.proxy.MonProxyFactory;

//import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

public class MonitorDataSource implements DataSource {

	private static final String interceptMethodName = "getConnection";

	private DataSource targetDataSource;

	public void setTargetDataSource(DataSource targetDataSource) {
		this.targetDataSource = targetDataSource;
	}

	private DataSource proxyDataSource;

	public MonitorDataSource() {
		this.proxyDataSource = (DataSource) Proxy.newProxyInstance(MonitorDataSource.class.getClassLoader(), new Class[] { DataSource.class }, new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				Object retVal = method.invoke(targetDataSource, args); // 执行目标方法且得到返回值
				if (interceptMethodName.equals(method.getName())) {
					return MonProxyFactory.monitor((Connection) retVal);
				}
				return retVal;
			}
		});
	}

	// 以下是被代理的方法

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return proxyDataSource.unwrap(iface);
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return proxyDataSource.isWrapperFor(iface);
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return proxyDataSource.getLogWriter();
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		proxyDataSource.setLogWriter(out);
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		proxyDataSource.setLoginTimeout(seconds);
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		return proxyDataSource.getLoginTimeout();
	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return proxyDataSource.getParentLogger();
	}

	@Override
	public Connection getConnection() throws SQLException {
		return proxyDataSource.getConnection();
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		return proxyDataSource.getConnection(username, password);
	}

}

 

你可能感兴趣的:(proxy)