Search code examples
javajacksonjackson-databind

compile and run java with jar files


I'm trying to compile a java file that uses multiple jar files as imports. the command that I have used to compile my code :

javac -cp jackson-databind-2.12.1.jar:jackson-core-2.12.1.jar:jackson-annotations-2.12.1.jar TestRunner.java

as a result two .class files are created : TestRunner.class and TestRunner$1.class

then I run the command :

java TestRunner

but it throws an error that says:

Error: Unable to initialize main class TestRunner Caused by: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/type/TypeReference

I have included all the required libraries in the javac command, tested it with the IDE and it works fine. I have tried other versions of the jackson library but I'm stuck with the same error.


Solution

  • You need to specify the classpath when running your code, by using the same -cp args that you used when compiling, plus the folder where your compiled class is in.

    In your cas that would mean something like java -cp .:jackson-databind-2.12.1.jar:jackson-core-2.12.1.jar:jackson-annotations-2.12.1.jar TestRunner

    The libs you specified are not included in the .class files generated, so Java still needs them to understand how to call the code that's not coming from your class file.