Can't import 3rd-party class in a separate class file


(GentleMint) #1

If writing below code in build.gradle, it works fine.

buildscript {
repositories {
jcenter()
mavenCentral()
}

dependencies {
    classpath group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.1'
}

}
import com.fasterxml.jackson.databind.ObjectMapper;
public class A {
}

If move the class A into a separate java file (content is as below), the import part will fail - can not find class com.fasterxml.jackson.databind.ObjectMapper.

import com.fasterxml.jackson.databind.ObjectMapper;
public class A {
}

I have tried to add “build” in dependency block, it still doesn’t work.

dependencies {
    build group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.1' 
}

How can I configure to make the separate java class file to be able to import the 3rd-party dependency class?


(GentleMint) #2

There is no way to acommplish such requirement?


(René Groeschke) #3

Where did you move class A? In general you should be fine declaring the buildscript block as you have it in your example on root project.


(GentleMint) #4

I moved it to src/main/gradle/ folder


(Stefan Oehme) #5

If you want to move an inline class out of your buildscript, you’ll want to use the buildSrc project. See the user manual on organizing build logic.

There is no src/main/gradle.


(GentleMint) #6

I moved it to buildSrc but it still fails with error “package xx does not exist”.

I uploaded my code to github here: https://github.com/GentleMint/GradlePractice/tree/master/StandaloneGradleBuildClass.
The 3rdParty lib class is com.fasterxml.jackson.databind.ObjectMapper.
It can be imported in build.gradle, but fails if import it in buildSrc\src\main\java\com\manning\gia\ReleaseVersionTask.java.

Could you help to take a look?
Thanks very much.


(James Justinic) #7

It can be imported from build.gradle because you’ve declared the dependency on Jackson in your buildscript block. The buildscript block places the dependency on the classpath of your buildscript, but not on the compile classpath for the buildSrc project, which is built separately as the first step.

With your example on GitHub, you need to declare the Jackson dependencies in buildSrc/build.gradle as that’s the project that’s trying to use them. You do not need to declare any dependencies in build.gradle as the compiled ReleaseVersionTask is automatically on the classpath of your buildscript in the StandAloneGradleClass folder due to it being in buildSrc.

build.gradle:

import com.manning.gia.ReleaseVersionTask

task t1 (type: ReleaseVersionTask) << {
    println 'hello'
}

buildSrc/build.gradle:

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.8.1'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.1'
}

(GentleMint) #8

The problem is sloved. Thanks very much!