1、占位符解析器实现的目标

通过解析字符串中指定前后缀中的字符,并完成相应的功能。

在mybtias中的应用,主要是为了解析Mapper的xml中的sql语句#{}中的内容,识别当前sql语句的一些特性。

 

2、占位符解析器的通用算法类

(1)org.apache.ibatis.parsing.GenericTokenParser

public class GenericTokenParser {

  private final String openToken;
  private final String closeToken;
  private final TokenHandler handler;

  public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
    this.openToken = openToken;
    this.closeToken = closeToken;
    this.handler = handler;
  }

  public String parse(String text) {
    final StringBuilder builder = new StringBuilder();
    final StringBuilder expression = new StringBuilder();
    if (text != null && text.length() > 0) {
      char[] src = text.toCharArray();
      int offset = 0;
      // search open token
      int start = text.indexOf(openToken, offset);
      while (start > -1) {
        if (start > 0 && src[start - 1] == '\\') {
          // this open token is escaped. remove the backslash and continue.
          builder.append(src, offset, start - offset - 1).append(openToken);
          offset = start + openToken.length();
        } else {
          // found open token. let's search close token.
          expression.setLength(0);
          builder.append(src, offset, start - offset);
          offset = start + openToken.length();
          int end = text.indexOf(closeToken, offset);
          while (end > -1) {
            if (end > offset && src[end - 1] == '\\') {
              // this close token is escaped. remove the backslash and continue.
              expression.append(src, offset, end - offset - 1).append(closeToken);
              offset = end + closeToken.length();
              end = text.indexOf(closeToken, offset);
            } else {
              expression.append(src, offset, end - offset);
              offset = end + closeToken.length();
              break;
            }
          }
          if (end == -1) {
            // close token was not found.
            builder.append(src, start, src.length - start);
            offset = src.length;
          } else {
            builder.append(handler.handleToken(expression.toString()));
            offset = end + closeToken.length();
          }
        }
        start = text.indexOf(openToken, offset);
      }
      if (offset < src.length) {
        builder.append(src, offset, src.length - offset);
      }
    }
    return builder.toString();
  }
}
View Code

相关文章:

  • 2023-02-10
  • 2022-02-21
  • 2021-08-15
  • 2021-12-31
  • 2022-12-23
  • 2021-12-06
  • 2022-02-08
  • 2021-10-31
猜你喜欢
  • 2022-02-18
  • 2021-09-12
  • 2021-10-17
  • 2021-07-01
  • 2021-11-08
  • 2021-05-03
  • 2022-01-14
相关资源
相似解决方案