Search code examples
javaantlr4grun

ANTLR4 TestRig (grun) throws java.lang.NoClassDefFoundError exception


I'm trying to learn ANTLR 4, and I'm following the examples given in The Definitive ANTLR 4 Reference. Sadly I'm stuck at the first example.


System:
Windows 10 (1703)
Java 8, update 151
ANTLR 4, v4.7

My %CLASSPATH% is set as a system variable (.;"D:\Program Files\Java\libs\antlr-4.7-complete.jar";).
I have antlr4.bat and grun.bat available in my %PATH%, and I'm able to run antlr4 from the command line.

antlr4.bat : java -cp %CLASSPATH% org.antlr.v4.Tool %*
grun.bat : java -cp %CLASSPATH% org.antlr.v4.gui.TestRig %*

I'm using -cp %CLASSPATH% explicitly because I've seen a few others having problems when not using the -cp option.


My problem is this:
When I run grun on the example grammar Hello (grun Hello r -tokens) I get this error message

Exception in thread "main" java.lang.NoClassDefFoundError: HelloLexer (wrong name: main/resource/hello/HelloLexer)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.antlr.v4.gui.TestRig.process(TestRig.java:129)
        at org.antlr.v4.gui.TestRig.main(TestRig.java:119)

Any ideas to what I'm doing wrong?
Many thanks in advance!


EDIT:
I thought I had found an answer. By cd-ing into the folder where the compiled files were (instead of calling grun from the root project folder) I managed to get through the example in question.

But when I tried to set up my own project, I came across the same issue, with the same error message as above.

This time, it seems like grun is complaining after I've run antlr4 with the -package option.

Does anyone know why this is?


Solution

  • Wow... The solution was, of course, an easy solution... My problem was that I had cd'd to the root folder of my test project, and I just had to cd to (and call grun from) the directory where the compiled files are.

    Edit:
    It seems like I still have an issue with grun. See edited question.

    Edit2:
    From what I can tell, grun doesn't cooperate very well with antlr4's -package option.
    So my solution was that I had to set up my project as a Gradle project, because apparently that works better.