0

I have a project my_project. I would like to compile it and after compilation I would like to access some classes which are in that project, e.g. create new object MyDataClass and print it.

This is what I am trying to do in my build.gradle:

doLast {
    MyDataClass toPrint = new MyDataClass()
    System.out.println(toPrint)
}

I think I have to somehow specify classpath in buildscript block for my_project but I really new to gradle and I do not know how how to do that.

Thank you for any help.

Druudik
  • 955
  • 1
  • 10
  • 32

1 Answers1

0

You should be able to get what you need from sourceSets.gradlebuilds.runtimeClasspath

Assuming your sourceSets have been declared properly. https://docs.gradle.org/current/dsl/org.gradle.api.tasks.SourceSet.html

I would have to see your build.gradle to get a better idea of what you're trying to accomplish but it may be easier to create a java class and call it from a JavaExec task

task(runApplication,  type: JavaExec) {  
    main = 'com.druudik.MyNewDataClass' //need main method in this java file  
    classpath = sourceSets.gradlebuilds.runtimeClasspath  
    args 'arg1', 'arg2'  
}
  • I was looking for some example but I could not find any. How can I access class ? – Druudik Feb 04 '19 at 17:36
  • I've updated the post with an example you may find helpful. If not I'll need further info – jonathanlevis Feb 04 '19 at 18:10
  • I would like to work with classes of my project like in the example not just call main method. In other words if it is possible I would like to create new object of my class using `new` keyword and then work with it like in normal groovy code. – Druudik Feb 04 '19 at 18:54
  • 1
    Have you seen this post? https://stackoverflow.com/questions/26314709/use-java-class-in-gradle-build-script – jonathanlevis Feb 04 '19 at 19:10
  • This is definitely helpful but the problem is that I want to use class which will be compiled during run of my script. In other words in build.gradle I want to compile my code, create jar and then use that jar which I have just created for my doLast task. My jar does not exist on startup of the script since it is going to be created. – Druudik Feb 04 '19 at 19:44
  • The compiled jar files will be located in sourceSets.gradlebuilds.runtimeClasspath you should be able to simply add that in your task prior to instantiating MyDataClass `classpath = sourceSets.gradlebuilds.runtimeClasspath` – jonathanlevis Feb 04 '19 at 19:53
  • Try classpath += sourceSets.gradlebuilds.runtimeClasspath If that doesn't work, run println classpath and see what comes out – jonathanlevis Feb 04 '19 at 20:11
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/187888/discussion-between-jonathanlevis-and-druudik). – jonathanlevis Feb 04 '19 at 20:27