标签:
说深入理解其实是有些过了,只能算是肤浅的理解,这技术叫代理,似乎跟设计模式扯上点关系,因此显得有些NB,还是动态的,这逼格就更高了。对于逼格高的东西,我一向喜欢扒一扒。
public static ResultSet createResultSetJPWrapper(ResultSet rs) { return (ResultSet)(Proxy.newProxyInstance(ResultSet.class.getClassLoader(), new Class[] {ResultSet.class}, new ResultSetJPWrapper(rs))); } private static class ResultSetJPWrapper implements InvocationHandler { private ResultSet wrappedResultSet; public ResultSetJPWrapper(ResultSet rs) { wrappedResultSet = rs; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(wrappedResultSet, args); if ("getString".equals(method.getName()) && null != result) { result = CommonUtils.convertCharset((String)result, ISAConstants.CHARSET_8859_1, ISAConstants.CHARSET_UTF_8); } return result; } } public static PreparedStatement createPreparedStatementJPWrapper(PreparedStatement pstmt) { return (PreparedStatement)(Proxy.newProxyInstance(PreparedStatement.class.getClassLoader(), new Class[] {PreparedStatement.class}, new PreparedStatementJPWrapper(pstmt))); } private static class PreparedStatementJPWrapper implements InvocationHandler { private PreparedStatement wrappedStatement; public PreparedStatementJPWrapper(PreparedStatement pstmt) { wrappedStatement = pstmt; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("setString".equals(method.getName()) && args.length == 2 && null != args[1] && String.class.equals(args[1].getClass())) { args[1] = CommonUtils.convertCharset((String)args[1], ISAConstants.CHARSET_UTF_8, ISAConstants.CHARSET_8859_1); } return method.invoke(wrappedStatement, args); } }
// 重构前 PreparedStatement stmt = conn.prepareStatement(sql); // 重构后 PreparedStatement stmt = DBUtils.createPreparedStatementJPWrapper(conn.prepareStatement(sql)); // 重构前 ResultSet rs = stmt.executeQuery(); // 重构后 ResultSet rs = DBUtils.createResultSetJPWrapper(stmt.executeQuery());
标签:
原文地址:http://www.cnblogs.com/jiyuqi/p/4432452.html