Vaijnath Polsane
Vaijnath Polsane

Reputation: 657

call java function in gradle script

I have a java class which does some kind of functionality, one of these function returns something that I need to use it into gradle script to set the project properties.
I had achieved it by creating an artifact of project and used that artifact by adding it into classpath, that gave me accessibility of that class and function.

buildscript {
  repositories {
    jcenter()
    maven{
      url 'http:localhost:8081/artifactory/temp'
    }
  }

  dependencies { 
    classpath "utility:sampleutility:1.0"
  }
}

import com.polsys.utility.MyUtil
dependencies {
    compile 'org.slf4j:slf4j-api:1.7.13'
    compile 'HRP:'+new MyUtil().callMe()+':1.0'
    //callme function returns the name of artifact. 
    testCompile 'junit:junit:4.12'
}

Now, I had achieved it by the way as mentioned above that is by creating artifact, add that artifact into classpath, then import classes and use function. Is this any way by which I can call functions of current project? so I can merge that functionality which is available in the artifact into current project.

Upvotes: 4

Views: 3819

Answers (2)

Vaijnath Polsane
Vaijnath Polsane

Reputation: 657

To make your java code available to gradle script you need to have your java code under the directory hierarchy given below:

  • ProjectRootDirectory
    • buildSrc
      • src
        • main
          • groovy/java
            • YourPackages(in my case java packages and classes)

This is the path where gradle script looking for external plugins. Now you can import and access classes into gradle script(you will not end up with "unable to resolve class" error).

Upvotes: 3

Radim
Radim

Reputation: 4808

Simple way is to put your Java/Groovy code under buildSrc dir. Gradle will compile it and you'll be able to call this code from your buildscript. Check https://docs.gradle.org/current/userguide/custom_plugins.html and related docs.

Upvotes: 3

Related Questions