0

Sometimes i use sublime+cmd with small examples. I've downloaded some .jar's, added them to lib directory of my project, imported necessary classes.



    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.databind.ObjectMapper;


Compiled this way:

javac Example.java -classpath ./lib/;./lib/jackson-core-2.12.5.jar;./lib/jackson-databind-2.12.5.jar;./lib/jackson-annotations-2.12.5.jar

after the launch (java Example) it gives the response:

Exception in thread "main" java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper
        at Example.convertToJSON(Example.java:55)
        at Example.main(Example.java:49)
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.ObjectMapper
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
        ... 2 more

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
tegowai
  • 81
  • 1
  • 1
  • 8
  • 3
    You also need to specify the classpath when **running** your application with `java`. Only specifying the classpath when compiling is not sufficient. – Mark Rotteveel Aug 28 '21 at 13:05
  • 1
    maybe it's time to look for tools that might make your life easier, like maven or gradle. – rkosegi Aug 28 '21 at 13:13
  • *`javac Example.java -classpath ./lib/;./lib/jackson-core-2.12.5.jar;./lib/jackson-databind-2.12.5.jar;./lib/jackson-annotations-2.12.5.jar`* You are giving javac mixed signals. You have Windows path separators and Unix file separators. afaik (unlike with Java code) javac will not accept forward slashes on Windows. *Which* OS are you using? – g00se Aug 28 '21 at 13:16
  • @g00se using forward slash on Windows will work just fine – Mark Rotteveel Aug 29 '21 at 08:38
  • You're probably right, but I've got to do something in Windows soon so I'll try it for myself – g00se Aug 29 '21 at 10:08

2 Answers2

0

Java is dynamically linked. Compiling with ceratin JARs in the classpath does not "embed" them in your jar, and you'll also need to supply them in the classpath when executing your program:

java -cp ./lib/;./lib/jackson-core-2.12.5.jar;./lib/jackson-databind-2.12.5.jar;./lib/jackson-annotations-2.12.5.jar com.mypackage.Example
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You should specify the classpath containing all the dependencies that has been use to compile your code using the -cp java command switch option:

java -cp .;.\lib\* Example

Note the usage of the * asterisk which allow the classpath to expand to all files under the ./lib folder.

You can also set the runtime classpath using the environment variable CLASSPATH with a value being the same as the one used in command line.

tmarwen
  • 15,750
  • 5
  • 43
  • 62