How does Java decide where to look for the main class?

I have a bunch of .jar files in a folder called "delivered."

/target /staged - akka-slf4j_2.10.0-RC1-2.1.0-RC1.jar - play_2.10-2.1-RC1.jar - etc... 

While my current directory is "target", I'm trying to run the command

 $ java -cp ./staged/* play.core.server.NettyServer ./.. Error: Could not find or load main class ..staged.akka-slf4j_2.10.0-RC1-2.1.0-RC1.jar 

It looks like Java is looking for the main class in staged.akka-slf4j_2.10.0-RC1-2.1.0-RC1.jar. The NettyServer class is in a completely different .jar file called play_2.10-2.1-RC1.jar. How does Java decide which .jar files to look for in order to find the main method?

+4
source share
5 answers

You get this error because the class path should contain its entries, separated by colons : and not a space. When the shell expands on target/* , it puts spaces between each file, which makes Java β€œthink” that only the first jar file is in the class path, that the second jar file is the name of the class you want to run, and that rest is command line options that should be passed to main .

If you specify the path, java expands * the list of files with the correct delimiter:

 java -cp "./staged/*" play.core.server.NettyServer ./.. 

See also other ways to create class paths from all files in a directory in this question .

+1
source

Java is not looking for a specific jar file. It just looks for the resulting classpath for the class specified on the command line.

Edit: if you do not specify "-jar", in this case it uses the Main-Class directive of the MANIFEST.MF file.

+4
source

In MANIFEST.MF you need to write a line like this:

 Main-Class: MyPackage.MyClass 

Then add this manifest to your jar, and the jar knows where to look.

+1
source

There, the MANIFEST.MF file in your .jar is placed in the META-INF folder.

You can create a new one if it does not exist.

http://docs.oracle.com/javase/tutorial/deployment/jar/defman.html

Content example:

 Manifest-Version: 1.0 Created-By: 1.7.0_06 (Oracle Corporation) Main-Class: org.package.MainClass 
+1
source

Shell extends your command line

 java -cp ./staged/* play.core.server.NettyServer ./.. 

eg,

 java -cp ./staged/play_2.10-2.1-RC1.jar ./staged/akka-slf4j_2.10.0-RC1-2.1.0-RC1.jar ... play.core.server.NettyServer ./.. 

Java now has ./staged/play_2.10-2.1-RC1.jar as the classpath and ./staged/akka-slf4j_2.10.0-RC1-2.1.0-RC1.jar first argument, where it searches for the main class.

0
source

All Articles