共计 2433 个字符,预计需要花费 7 分钟才能阅读完成。
序
本文主要研究一下 sharding-jdbc 的 WrapperAdapter
Wrapper
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;
}
- Wrapper 接口定义了 unwrap、isWrapperFor 方法
WrapperAdapter
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);
}
}
}
- WrapperAdapter 声明实现 java.sql.Wrapper 接口,它定义了 JdbcMethodInvocation 集合;recordMethodInvocation 方法会往 jdbcMethodInvocations 添加 JdbcMethodInvocation;replayMethodsInvocation 方法则会挨个执行 JdbcMethodInvocation 的 invoke 方法
JdbcMethodInvocation
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);
}
}
- JdbcMethodInvocation 的 invoke 方法执行的是 method.invoke
小结
WrapperAdapter 声明实现 java.sql.Wrapper 接口,它定义了 JdbcMethodInvocation 集合;recordMethodInvocation 方法会往 jdbcMethodInvocations 添加 JdbcMethodInvocation;replayMethodsInvocation 方法则会挨个执行 JdbcMethodInvocation 的 invoke 方法
doc
- WrapperAdapter
正文完
发表至:无分类
2019-08-10