Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner classes not being included in jar file

I hava made a runnable jar file out of six classes:

Main: Contains the main method, and specified in the manifest (I included a new line)

Main$1 and Main$2: 2 anonymous inner classes that are in the main class. (Main$2 is in the main method, but I don't think that really matters.)

Form

Form$1: An anonymous inner class in Form

WrapLayout

I specify these inner classes when making the jar file, but when I look inside it (I am on mac) the inner classes are not in the jar! So when I run it, I get this:

 Exception in thread "main" java.lang.NoClassDefFoundError: Main$2
    at Main.main(Main.java:64)
 Caused by: java.lang.ClassNotFoundException: Main$2
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 1 more

I can't figure out what's wrong. Can somebody please help?

EDIT: I figured it out! Turns out, you need an escape character (\) in front of the dollar signs for the command to recognize them.

like image 467
user1605892 Avatar asked Aug 19 '12 01:08

user1605892


People also ask

Does JAR file contain class files?

The JAR file contains the TicTacToe class file and the audio and images directory, as expected. The output also shows that the JAR file contains a default manifest file, META-INF/MANIFEST. MF, which was automatically placed in the archive by the JAR tool.

How do you declare an inner class?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.


1 Answers

You already found your specific answer, but here's a more general one.

As your modify your program, the set of classes with automatically generated names (e.g., Main$2) will change. Also, if you move your classes into a named package, your jar file will have to have a parallel directory structure. You don't want to have to update your makefile or build script every time this happens. Instead, you should use javac -d to specify a destination directory for the compiled class files, and then jar up this entire hierarchy.

like image 124
Stuart Marks Avatar answered Sep 20 '22 21:09

Stuart Marks