Use class from java sourceset within gradle script?


(Shaw) #1

I have a class that is built from:

src/main/java/somewhere/SomeClass.java

within build.gradle I want to reference that class in logic for tests, e.g.

task someTask(type: Test) {
if (“bork” in SomeClass.class.getAnnotation(Blah.class).value())
println “hurray”
}

how can I get SomeClass to be among dependencies for the buildScript?


(Stefan Oehme) #2

It should not be in the production code, but in the buildSrc project to be available to your buildscript.

Have a look at the user guide about organizing build logic.


(Shaw) #3

The point of of having the build script at all is to build the production code. I want to make use of one of the classes that is in production code within build logic.


(Stefan Oehme) #4

You have a chicken-and-egg problem here:

  • “I need the production code to compile my buildscript”
  • “I need my buildscript to compile the production code”

You cannot reference your production classes directly from the buildscript.

What you can do is loading that class into a UrlClassLoader and then analyze it using reflection. Or use a library like ASM if it needs to be extra fast.


(davidmichaelkarr) #5

Or perhaps refactor this into a multi-module project, where “SomeClass” is in a separate module that is a dependency of both the buildscript and the other production code.


(Shaw) #6

It is essentially the same sort of idea as test classes needing to be able to find the classes that they test. One stage of the build process depends on another stage of the build process.

Plugins that allow a compiler compiler to be incorporated into a build is another similar sort of idea where one stage of the build process depends on another stage of the build process and it is beyond the stages of compile and test.

An approach that requires me to change the layout of the software in order to accommodate the build system makes me think that that is not the best approach.

Using UrlClassLoader seems hackish, but maybe not that bad. It is reflection that I am trying to use.

Can I set the class path used by the build script from the output of a task instead?

Kendall


(Lance Java) #7

As mentioned in other answers, the buildscript classpath is resolved before the classes are compiled hence the chicken and egg problem.

UrlClassLoader has been mentioned as one solution. Another solution could use qdox to get the annotations from the Java sources instead of relying on class files