嵌套类: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);
          }
        }
      }
    }
  }
csfkk 回答:嵌套类:OuterClass.this.someAttribute

SqlSessionManager.this指的是外部类,如果您只是使用this,则它指的是没有SqlSessionInterceptor的{​​{1}}。

如果仅使用localSqlSession,它将引用直接外部类。如果在localSqlSessionSqlSessionManager之间还有另一个externalClass,则它将引用该类而不是SqlSessionInterceptor。明确添加SqlSessionManager会声明使用SqlSessionManager.this

中存在的那个

请参阅: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,看来这样做只是为了提高可读性。

本文链接:https://www.f2er.com/2865428.html

大家都在问