本文主要研究一下sharding-jdbc的WrapperAdapter
jdk-12.jdk/Contents/Home/lib/src.zip!/java.sql/java/sql/Wrapper.java
public interface Wrapper { <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException; boolean isWrapperFor(java.lang.Class<?> iface) throws java.sql.SQLException; }
incubator-shardingsphere-4.0.0-RC1/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/adapter/WrapperAdapter.java
public abstract class WrapperAdapter implements Wrapper { private final Collection<JdbcMethodInvocation> jdbcMethodInvocations = new ArrayList<>(); @SuppressWarnings("unchecked") @Override public final <T> T unwrap(final Class<T> iface) throws SQLException { if (isWrapperFor(iface)) { return (T) this; } throw new SQLException(String.format("[%s] cannot be unwrapped as [%s]", getClass().getName(), iface.getName())); } @Override public final boolean isWrapperFor(final Class<?> iface) { return iface.isInstance(this); } /** * record method invocation. * * @param targetClass target class * @param methodName method name * @param argumentTypes argument types * @param arguments arguments */ @SneakyThrows public final void recordMethodInvocation(final Class<?> targetClass, final String methodName, final Class<?>[] argumentTypes, final Object[] arguments) { jdbcMethodInvocations.add(new JdbcMethodInvocation(targetClass.getMethod(methodName, argumentTypes), arguments)); } /** * Replay methods invocation. * * @param target target object */ public final void replayMethodsInvocation(final Object target) { for (JdbcMethodInvocation each : jdbcMethodInvocations) { each.invoke(target); } } }
incubator-shardingsphere-4.0.0-RC1/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocation.java
@RequiredArgsConstructor public class JdbcMethodInvocation { @Getter private final Method method; @Getter private final Object[] arguments; /** * Invoke JDBC method. * * @param target target object */ @SneakyThrows public void invoke(final Object target) { method.invoke(target, arguments); } }
WrapperAdapter声明实现java.sql.Wrapper接口,它定义了JdbcMethodInvocation集合;recordMethodInvocation方法会往jdbcMethodInvocations添加JdbcMethodInvocation;replayMethodsInvocation方法则会挨个执行JdbcMethodInvocation的invoke方法