Home > front end >  gradle does not import local java libraries
gradle does not import local java libraries

Time:12-19

I have the following folder structure:

-bin

-build/build.gradle (the gradle script)

-lib/[*.jar] (libraries that the project is using)

-src/folder/folder/[*.java] (project's source code)

The following content for the build.gradle script:

plugins {
    id 'java'
    id 'groovy'
}

buildDir = new File('../bin') 
sourceCompatibility = JavaVersion.VERSION_1_8 

sourceSets { 
    main { 
        java { 
            allJava.srcDirs = [ '../src/folder/folder/ '] 
            compileClasspath = fileTree('../bin') 
        } 
    } 
} 

repositories {
    flatDir {
        dirs '../lib'
    }
}

dependencies {
    implementation fileTree('../lib')
}

tasks.register('javac', JavaCompile) { 
    println 'Call javac' 
    source.forEach { e -> println e} 

    classpath = sourceSets.main.compileClasspath 
    destinationDirectory = file('../bin') 
    source sourceSets.main.allJava.srcDirs 
    includes.add('*.java') 
    sourceCompatibility = JavaVersion.VERSION_1_8 
}

When running gradle javac I got the error: error: cannot find symbol import com...

The documentations clearly says:

dependencies {
.
.
.
    //putting all jars from 'libs' onto compile classpath
    implementation fileTree('libs')
}

I'm using Gradle 7.3.1

CodePudding user response:

Allow me to give you some general advice first. I can strongly recommend using the Kotlin DSL instead of the Groovy DSL. You instantly get strongly typed code in the build scripts and much better IDE support.

Also you should imho consider changing your project layout to be more like most other Java projects out there and especially not use a libs directory, but use normal dependencies in a repository where transitive dependencies are then handled automatically and so on.

But to answer your actual question, this is the build complete build script in Groovy DSL that you want:

plugins {
    id 'java'
}

buildDir = '../bin'

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(8))
    }
}

sourceSets {
    main {
        java {
            srcDirs = ['../src/folder/folder']
        }
    }
}

dependencies {
    implementation fileTree('../lib')
}

And this is the matching Kotlin DSL version:

plugins {
    java
}

setBuildDir("../bin")

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(8))
    }
}

sourceSets {
    main {
        java {
            setSrcDirs(listOf("../src/folder/folder"))
        }
    }
}

dependencies {
    implementation(fileTree("../lib"))
}
  • Related