`
feiruqueshui
  • 浏览: 5425 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

java核心基础--动态代理

    博客分类:
  • java
阅读更多
/**
 * SqlReporter.
 */
public class SqlReporter implements InvocationHandler {
	
	private Connection conn;
	private static boolean loggerOn = false;
	private static final Logger log = Logger.getLogger(SqlReporter.class);
	
	SqlReporter(Connection conn) {
		this.conn = conn;
	}
	
	public static void setLogger(boolean on) {
		SqlReporter.loggerOn = on;
	}
	
	@SuppressWarnings("rawtypes")
	Connection getConnection() {
		Class clazz = conn.getClass();
		return (Connection)Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{Connection.class}, this);
	}
	
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		try {
			if (method.getName().equals("prepareStatement")) {
				String info = "Sql: " + args[0];
				if (loggerOn)
					log.info(info);
				else
					System.out.println(info);
			}
			return method.invoke(conn, args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
	}
}

 


最近看jfinal源码,熟悉框架构造的时候,发现的一个学习点。

代理对象和真实业务对象。

直接代码:



 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics