嵌套类:`OuterClass.this.someAttribute`?

问题描述 投票:0回答:1

嗨,我正在阅读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);
          }
        }
      }
    }
  }
java mybatis inner-classes
1个回答
0
投票

[SqlSessionManager.this指的是外部类,如果您只使用了this,它将指的是没有SqlSessionInterceptorlocalSqlSession

如果仅使用localSqlSession,它将引用直接外部类。如果SqlSessionManagerSqlSessionInterceptor之间还有另一个externalClass,则它将引用该类而不是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,看来这样做只是为了提高可读性。

© www.soinside.com 2019 - 2024. All rights reserved.