Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio: Dependencies not included in Java module using Gradle 4.1

I have a Java module that generates some metadata for my Android app and needs to run as a regular Java application. After updating to Android Studio 3.0 (in 2.3.3 it worked as expected) I get a NoClassDefFoundError for the dependencies (in the case below for com/google/gson/GsonBuilder, the main method itself can be found).

I even tried putting the GSON Jar into the libs folder but it still throws the NoClassDefFoundError.

I assume the dependencies are not properly included. Any idea how to fix this?

The build.gradle looks like this:

apply plugin: 'java'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.code.gson:gson:2.8.1'
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"

My class looks like this:

import com.google.gson.GsonBuilder;

public class myClass {
    public static void main(String[] args) {
        GsonBuilder builder = new GsonBuilder();
    }
}
like image 318
jeff_bordon Avatar asked Mar 12 '26 11:03

jeff_bordon


1 Answers

Use api instead of implementation.

From the docs

When your module configures an implementation dependency, it's letting Gradle know that the module does not want to leak the dependency to other modules at compile time. That is, the dependency is available to other modules only at runtime.

Using this dependency configuration instead of api or compile can result in significant build time improvements because it reduces the amount of projects that the build system needs to recompile. For example, if an implementation dependency changes its API, Gradle recompiles only that dependency and the modules that directly depend on it. Most app and test modules should use this configuration.

See difference between api and implementation here for more info.

like image 99
Nongthonbam Tonthoi Avatar answered Mar 15 '26 01:03

Nongthonbam Tonthoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!