首页 > 解决方案 > 嵌套类:`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);
          }
        }
      }
    }
  }

标签: javamybatisinner-classes

解决方案


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,似乎这样做只是为了便于阅读。


推荐阅读