Search code examples
javajarnoclassdeffounderrorclassnotfoundexception

NoClassDefFoundError in app, classpath is correct (at first sight). Why?


I run my app.jar as java -jar app.jar and see the next error:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/thrift/transport/TTransportException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.apache.thrift.transport.TTransportException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more

app.jar structure:

    .
    ├── lib
    │   ├── ... (some *.jar files)
    │   ├── libthrift-0.9.3.jar
    │   └── ... (some *.jar files)
    ├── META-INF
    │   ├── MANIFEST.MF
    │   └── maven
    │       └── groupId-name
    │           └── artifactId-name
    │               ├── pom.properties
    │               └── pom.xml
    └── ... *.class files of app

In META-INF/MANIFEST.MF declared a classpath as:

Class-Path: lib/libthrift-0.9.3.jar lib/...(other *.jar's from lib/ folder)

libthrift-0.9.3.jar structure:

    .
    ├── META-INF
    │   ├── LICENSE.txt
    │   ├── MANIFEST.MF
    │   └── NOTICE.txt
    └── org
        └── apache
            └── ... some packages with files
                ├── transport
                │   ├── ... some files
                │   ├── TTransportException.class
                │   └── ...
                └── ...

As are you see, class org.apache.transport.TTransportException exists and must be accessible in runtime. But don't. Why so?


Solution

  • First: by default in java if you have not used any special tools/frameworks (like spring-boot) you cannot have jars inside jar.

    Second: The entries in in your Manifest file (like Class-Path: lib/libthrift-0.9.3.jar etc) reference not the jars inside jar but the jars in file system near the jar. I.e the file structure to run your app with java -jar app.jar should be:

    ./
     /libs --> all 3-d party jars here
     app.jar
    

    If you want to have all in one jar one of the variants is to use so called 'uber-jar' - in that case all the 3-d party classes are extracted from their jars and packaged together with your own classes in one jar.

    For example for maven build Shade Plugin can be used.