SeeMoreGain
SeeMoreGain

Reputation: 1273

Java Jar - classpath issue

Running out of ideas on the cause of the issue. I have a java jar (built from gradle under intellij if that matters).

What am I missing (apart from more and more chunks of hair off my head)?

Edit Additional details: - using Java 8

jar structure:

-META-INF
  MANIFEST.MF
-companyname
  -module
    -interfaces
      interface1.class
    -commands
      baseCommand.class
      register.class
      specialCommand.class
    moduleSpec.class
    moduleProcessor.class
  mainclass.class
log4j.xml
springconfig1.xml
springconfig2.xml

Manifest file:

Manifest-Version: 1.0
Main-Class: companyname.mainclass
(newline char here)
(newline char here)

Upvotes: 2

Views: 2976

Answers (3)

Sergey Bespalov
Sergey Bespalov

Reputation: 1766

Cause can be in case if your main class has a static initialization block which throws some errors at runtime.

Upvotes: 0

Jason Hoetger
Jason Hoetger

Reputation: 8127

First, make sure you're creating the executable jar correctly. See this answer for info on creating an executable jar using gradle.

If you're creating and packaging your jar correctly, it's possible that it can't load your main class because it has dependencies that cannot be found. You said:

All dependencies are in a /lib folder relative to jar so no classpath specified in manifest

If you mean that the lib folder is in the same folder on the filesystem as the .jar file, then your dependencies won't be found. The contents of that lib folder will not be automatically added to the jar's classpath. You can manually add them to the classpath of the java command, or you can add them to the manifest. If you add them to the classpath, you can use wildcards:

java -cp "MyJar.jar;lib/*" com.mycompany.MyMainClass

If you add them to the manifest, you can't use wildcards, so you need to specify each individual jar dependency under your lib directory. (See the Oracle tutorial on adding jars to the classpath for more info.)

If the lib directory is inside the jar (a "fat jar"), then there's no classpath that will help you: the default classloader will not load dependencies from within the executable jar. However, there are multiple tools that allow you to create a fat jar that includes all its dependencies, and distribute it as a single executable jar. Since you're using gradle, the gradle shadow plugin may be of use to you.

Upvotes: 2

Barry O'Neill
Barry O'Neill

Reputation: 435

The manifest will be of use here. Also, if you try

java -jar -verbose:class MyJar | grep mainclass 

It'll confirm if your class is being loaded. Oh - Also, are there a mix of JVMs at play here?

Ensure java -version shows a Java 8, since that's what you hint that Intellij/Gradle is building with.

Upvotes: 0

Related Questions