代码tool.process(grammar, false);
产生空指针异常。
请参见下面的代码:
package antlr;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.antlr.v4.Tool;
import org.antlr.v4.tool.Grammar;
import org.antlr.v4.tool.ast.GrammarRootAST;
import org.junit.Test;
// License : Apache License Version 2.0 https://www.apache.org/licenses/LICENSE-2.0
/**
*
* @author Peter <peter@quantr.hk>
*/
public class TestDynamicParser {
@Test
public void testDynamicParser() throws Exception {
Tool tool = new Tool();
String content = new String(Files.readAllBytes(Paths.get(getClass().getResource("Hello.g4").toURI())));
GrammarRootAST ast = tool.parseGrammarFromString(content);
Grammar grammar = tool.createGrammar(ast);
tool.process(grammar, false);
}
}
语法:
grammar Hello;
r : 'hello' ID;
ID : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
错误:
java.lang.NullPointerException
at antlr.TestDynamicParser.testDynamicParser(TestDynamicParser.java:23)
如何防止发生此错误?