java - 嵌套类:`OuterClass.this.someAttribute`?
问题描述
嗨,我正在阅读 myBatis 的源代码,但我的问题是我不明白这一行SqlSessionManager.this.localSqlSession.get()
。是什么意思SqlSessionManager.this
?
我的尝试:如果我没记错的话当创建一个嵌套类时说它A.B nestedObjectB = new A.B();
实际上为它创建了一个对象A.B
和一个匿名对象A
。所以我猜SqlSessionManager.this
是类似于A
这里的对象?
(在SqlSessionManager.java
)
private class SqlSessionInterceptor implements InvocationHandler {
public SqlSessionInterceptor() {
// Prevent Synthetic Access
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final SqlSession sqlSession = SqlSessionManager.this.localSqlSession.get(); // *
if (sqlSession != null) {
try {
return method.invoke(sqlSession, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
} else {
try (SqlSession autoSqlSession = openSession()) {
try {
final Object result = method.invoke(autoSqlSession, args);
autoSqlSession.commit();
return result;
} catch (Throwable t) {
autoSqlSession.rollback();
throw ExceptionUtil.unwrapThrowable(t);
}
}
}
}
}
解决方案
SqlSessionManager.this
指的是外部类,如果你只是使用this
它会指SqlSessionInterceptor
哪个没有localSqlSession
.
如果您只使用localSqlSession
它,它将引用直接的外部类。SqlSessionManager
如果和之间有另一个外部SqlSessionInterceptor
类,那么它将引用该类而不是SqlSessionManager
。添加SqlSessionManager.this
显式声明以使用存在于 SqlSessionManager
见:https ://stackoverflow.com/a/1816462/,https : //stackoverflow.com/a/5530293
编辑 :
参考https://github.com/mybatis/mybatis-3/blob/master/src/main/java/org/apache/ibatis/session/SqlSessionManager.java#L347,似乎这样做只是为了便于阅读。
推荐阅读
- python-3.x - 使用 re.search() 在字符串中搜索模式,模式包含 '+' 字符
- python - 从查找表更改列表的元素
- javascript - 从 Json 获取多个图像及其位置
- matlab - 使用 3 折交叉验证时,我的准确率为 0%
- javascript - 使用 Vue 组件制作复杂的表格布局
- postgresql - PostgreSQL SELECT 太慢了
- java - 以字符串形式给出的两个二进制数的乘法
- r - 如何使用 R 使用条形图按地区比较销售额
- angular - *ngFor 访问多个数组 Angular
- speech-recognition - Watson Speech to Text - 状态:401,错误:未经授权