我有一个名为“Test.g4”的ANTLR项目,我使用antlrworks2创建了没有任何问题的文件:Test.tokens,TestBaseListner.java,TestLexer.java,TestLexer.tokens,TestListener.java和TestParser.java.
现在我想在我的程序Test.java中使用语法:
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
public class Test {
public static void main(String[] args) throws Exception {
// create a CharStream that reads from standard input
ANTLRInputStream input = new ANTLRInputStream(System.in);
// create a lexer that feeds off of input CharStream
TestLexer lexer = new TestLexer(input);
// create a buffer of tokens pulled from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
// create a parser that feeds off the tokens buffer
TestParser parser = new TestParser(tokens);
ParseTree tree = parser.init(); // begin parsing at init rule
System.out.println(tree.toStringTree(parser)); // print LISP-style tree
}
}
当我尝试使用“javac -classpath /path/java2/antlr-4.4-complete.jar Test.java”编译它时,我得到以下错误:
Test.java:19: error: cannot find symbol
TestLexer lexer = new TestLexer(input);
^
symbol: class TestLexer
location: class Test
Test.java:19: error: cannot find symbol
TestLexer lexer = new TestLexer(input);
^
symbol: class TestLexer
location: class Test
Test.java:25: error: cannot find symbol
TestParser parser = new TestParser(tokens);
^
symbol: class TestParser
location: class Test
Test.java:25: error: cannot find symbol
TestParser parser = new TestParser(tokens);
^
symbol: class TestParser
location: class Test
4 errors
谢谢!
解决方法:
TestLexer.java和TestParser.java也应该在同一个命令中用Test.java编译,否则编译器将不知道在哪里查找它们的二进制文件.尝试按如下方式调用javac:
javac -classpath /path/java2/antlr-4.4-complete.jar *java
或者手动传递所有文件:
javac -classpath /path/java2/antlr-4.4-complete.jar Test.java TestLexer.java TestParser.java