Home > database >  Get NoClassDefFound Error in Apache Maven 3.8.6 (JDK-19 Gson2.10)
Get NoClassDefFound Error in Apache Maven 3.8.6 (JDK-19 Gson2.10)

Time:11-14

I am new to java and maven. I am learning and trying to make a system to help me build up JSON data by GOOGLE's gson and maven. This is my using command order:

mvn -f my-app\pom xml clean compile
mvn -f my-app\pom xml install
cd my-app\target
java -jar my-app-1.0.jar

After I run it it show me this error. enter image description here

in GSONExample.java Line 13:

Gson gson = new Gson();

The following is my using software/IDE version.

I have already gone through other websites and StackOverflow to find solutions.

GSON is not being imported into the maven project Changed scope role and still crash

error even though it is defined in my classpath /WEB-INF/lib can't find in my situation

Now below a part of my pom.xml

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10</version>
    </dependency>

I also had try to import it(Gson) to local and try to fix it out.

mvn install:install-file -Dfile=C:\gson-2.10.jar -DgroupId=com.myself.gson -DartifactId=example-gson -Dversion=2.10 -f my-app\pom.xml

After I use the command, I changed pom.xml as follow. It can compile and install. But still show me "NoClassDefFound"

    <dependency>
      <groupId>com.myself.gson</groupId>
      <artifactId>example-gson</artifactId>
      <version>2.10</version>
    </dependency>

May anyone provide any solution to this? Thanks in advance.

I had tried

  • changed scope to provided in pom.xml
  • put Gson in src\main\resources\lib and change pom.xml
  • Local gson-2.10.jar and change pom.xml
  • put gson-2.10.jar in C:\Program Files\apache-maven-3.8.6\lib

CodePudding user response:

The problem is this command:

java -jar my-app-1.0.jar

Most likely your current Maven pom.xml creates a JAR file which contains only the classes of your project, but not the classes of dependencies, such as Gson. This is also not specific to Gson but applies to any dependencies you are trying to use. You can either:

  • use java -cp and specify the path to your JAR as well as the paths to all the JARs of dependencies you are using, for example java -cp gson-2.10.jar;my-app-1.0.jar com.mycompany.app.GSONExample
  • configure Maven to build a "JAR with dependencies", see this question whose answers describe multiple ways of how this can be achieved
  • Related