I'm trying to use(import) a class added by a dependency of my project. I added the dependency gson in my pom.xml as follows:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
And I ran mvn install
after that.
Now I can find the jar dependencies in C:\Users\%Name%\.m2\repository\com\google\code\gson\gson\2.8.5
, so I assume it is correctly installed.
When I try to import the class Gson in Java, several problems occurs:
- The path to import isn't
com.google.code.gson
butcom.google.gson
, I don't understand why. When I compile with mvn package, everything runs smoothly. But if I try to run the code with
java -cp .\target\testJSON-1.0-SNAPSHOT.jar json.App
I get the following error telling me the Gson class isn't found :Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/Gson at json.App.main(App.java:13) 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) ... 1 more
Now from what I understood by looking for solutions:
While maven know the dependencies of the project, java
won't. And I need to manually add the jar to the classpath.
So my questions are:
- If I bother to tell maven I need gson to run my project, why do I need to manually include all dependencies to run it ? Is there a way to automate this thing in an easy and intuitive manner ?
- When I look for ways to add multiples jars to the classpath, the only answers I find assume that all the jars are in the same folder, hence proposing to do
java -cp folder/*.jar
. The jar generated by Maven is located in the target subfolder of my project, while the gson jar is located in the .m2 folder. How to add multiple jars (located in different locations) to the classpath ?
Thank you,