0

I'm trying to compile a jar file with my java program using javac -cp dependency.jar *.java and then run it using java -cp dependency.jar mainPrgram The program compiles just fine, and also runs fine, until a function call is made using the dependency.

Exception I get is below

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/Gson
        at DFS.readMetaData(DFS.java:250)
        at DFS.touch(DFS.java:111)
        at CommandLine.<init>(CommandLine.java:41)
        at CommandLine.main(CommandLine.java:132)
Caused by: java.lang.ClassNotFoundException: com.google.gson.Gson
        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)
        ... 4 more

Tried different solutions from

Why am I getting a NoClassDefFoundError in Java?

Class in jar not found at runtime, but was used to compile

But none seemed to work

UPDATE: The code runs fine within Eclipse, but not from the command line

After running it with eclipse, .classpath has the following:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
        <attributes>
            <attribute name="module" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="src" path=""/>
    <classpathentry kind="lib" path="C:/Users/MyPC/Documents/projects/MusicPlayer/gson-2.8.6.jar"/>
    <classpathentry kind="output" path=""/>
</classpath>
Mina Messiah
  • 119
  • 6
  • Eclipse adds transient dependencies to the class path when it starts the application. You should be able to see the command line used by eclipse. – kofemann Apr 29 '20 at 22:02

1 Answers1

0

Yor program is successfully completed against the jar. But the jar itself has a dependency that is required to run. You need to add all dependencies to the class path, like java -cp dependency.jar:subdependency.jar Main.

kofemann
  • 4,217
  • 1
  • 34
  • 39