编写 JavaCC 模板,*.jj 文件。
编译生成代码文件。
移动代码文件到对应的包下。
调用生成的代码文件。
main/javacc/SimpleSelectParser.jj
options {
IGNORE_CASE = true;
// 允许被多次初始化
STATIC = false;
}
PARSER_BEGIN(SimpleSelectParser)
package cn.com.ptpress.cdm.parser.select;
import java.io.* ;
public class SimpleSelectParser {
private String sql;
public void parse() throws ParseException {
SelectExpr(sql);
}
public SimpleSelectParser(String expr) {
this((Reader)(new StringReader(expr)));
this.sql = expr;
}
public static void main(String[] args) throws Exception{
final SimpleSelectParser parser = new SimpleSelectParser(String.join(" ", args));
parser.parse();
}
}
PARSER_END(SimpleSelectParser)
void SelectExpr(String sql) :
{
int res;
}
{
org.codehaus.mojo
javacc-maven-plugin
2.6
generate-sources
javacc
javacc
${basedir}/src/main/javacc
**/*.jj
${basedir}/generated-sources/
src/main/resources
mvn org.codehaus.mojo:javacc-maven-plugin:2.6:javacc
生成的文件:


package cn.com.ptpress.cdm.parser.select;
public class TestParser {
public static void main(String[] args) throws ParseException {
parseSelect("select 1+1");
parseSelect("select 1+1+1");
parseSelect("select 1 + 3 - 5");
}
private static void parseSelect(String sql) throws ParseException {
final SimpleSelectParser parser = new SimpleSelectParser(sql);
// 解析的核心方法
parser.parse();
}
}
