本人的JDK版本为1.8,需要生成的为了避免出现出现如下问题,自己选择的是antlr-4.8-complete.jar,而非最新的antlr-4.10.1-complete.jar
Execute has been compiled by a more recent version of the Java Runtime (class file version 55.0),
this version of the Java Runtime only recognizes class file versions up to 52.0
antlr4历史版本下载地址:website-antlr4/download/
将下载好的antlr-4.8-complete.jar放到指定目录,自己是/Users/xxx/antlr目录
由于没有root权限,只能修改当前用户的~/.bash_profile文件,添加如下内容:
# config antlr4
export CLASSPATH=".:/Users/xxx/antlr/antlr-4.8-complete.jar:$CLASSPATH"
alias antlr4='java -jar /Users/xxx/antlr/antlr-4.8-complete.jar'
alias grun='java org.antlr.v4.gui.TestRig'
使用source ~/.bash_profile使其生效
执行antlr4和grun命令,验证配置是否生效


Preferences ...
→
\rightarrow
→ Plugins
→
\rightarrow
→ Marketplace 中,输入antlr4,安装出现的ANTLR v4插件
ANTLR Preview的使用新建maven项目,在resources中,创建Hello.g4文件,内容如下:
grammar Hello;
r: 'hello' NAME;
NAME: [a-zA-Z]+;
WS: [ \t\r\n]+ -> skip;
这时,可以选中r这条parser rule,开启 ANTLR Preview已验证规则的正确性

本人做了如下验证,从parse tree来看,该rule书写正确

选中Hello.g4文件,右键
→
\rightarrow
→ Configure ANTLR ...,进行相关配置

完成配置后,再次选中Hello.g4文件,右键
→
\rightarrow
→ Generate ANTLR Recognizer,会在指定目录生成指定包名的Java代码

随便打开一个antlr4生成的Java文件,发现import处报错
缺少相关的依赖antlr4-runtime,在pom文件中加上即可
<dependency>
<groupId>org.antlrgroupId>
<artifactId>antlr4-runtimeartifactId>
<version>4.7.2version>
dependency>
除了使用IDEA的插件,还可以使用maven插件antlr4-maven-plugin
配置如下:
<plugin>
<groupId>org.antlrgroupId>
<artifactId>antlr4-maven-pluginartifactId>
<version>4.8version>
<executions>
<execution>
<id>antlrid>
<goals>
<goal>antlr4goal>
goals>
<phase>generate-sourcesphase>
execution>
executions>
<configuration>
<sourceDirectory>${basedir}/src/main/resourcessourceDirectory>
<outputDirectory>${basedir}/src/main/javaoutputDirectory>
<listener>truelistener>
<visitor>truevisitor>
<treatWarningsAsErrors>truetreatWarningsAsErrors>
configuration>
plugin>
最终在指定目录生成对应的Java文件

如果想生成指定package文件,改动如下:
Hello.g4中,添加通过@header指定package@header{
package com.sunrise.hello;
}
antlr4-maven-plugin的配置,将outputDirectory改为包路径<outputDirectory>${basedir}/src/main/java/com/sunrise/hellooutputDirectory>
之前配置了antlr4命令,可以通过antlr4命令生成Java代码
antlr4 Hello.g4 -package com.sunrise.hello -visitor -o ../java/com/sunrise/hello -Dlanguage=Java
-package,指定包名;-visitor,表示生成visitor代码,默认是不生成的;-o,指定Java代码的输出目录;-Dlanguage,指定代码语言,具体有哪些option可以查看官网
antlr4-maven-plugin的完美配置:Antlr4简明使用教程