How do I use Gradle to build a special JAR with only a subset of classes?

Viewed 1490

I have been given a project A that needs access to class files from another project B. More precisely, A only needs classes compiled from the B/ejb/C/src portion of the B/ tree:

B/ejb/C/src/com/company/admin/Foo.java
B/ejb/C/src/com/company/admin/FooHome.java
B/ejb/C/src/com/company/admin/FooBean.java
B/ejb/NOTNEEDED/src/com/company/data/...

The person who had this A project before used JBuilder and included in the source definition pointers to the parallel project's B/ejb/C/src. The A project builds a jar which includes classes compiled from this other tree. I'm trying to figure out how to do this using Gradle. I want to make a B/build.gradle in the B project that will create a B-C-version.jar of .class files compiled from these sources:

B/ejb/C/src/com/company/admin/Foo.java
B/ejb/C/src/com/company/admin/FooHome.java
B/ejb/C/src/com/company/admin/FooBean.java

that I would then publish to Maven and access from the A project.

i.e., the B-C-version.jar would ideally only have these classes:

com/company/admin/Foo.class
com/company/admin/FooHome.class

but if B-C-version.jar had these classes:

com/company/admin/*.class

that would also be OK. How can I make such a thing using a build.gradle in the B project?

1 Answers

You can simply declare a custom Jar task like

task cJar(type: Jar) {
   baseName = project.name + '-C'
   from sourceSets.main.output
   include 'com/company/admin/Foo.class', 'com/company/admin/FooHome.class'
}

or you can make a dedicated sourceset for your api that you then use from your other B code and from your A code, then you don't need to work with includes and update the include if you need to add files, but you just place them in the source folder of the source set and you are done, something like

sourceSets { c }

task cJar(type: Jar) {
   baseName = project.name + '-C'
   from sourceSets.c.output
}

Then you could also declare dependencies separately and get the correct ones drawn in transitively and so on. But it might be overkill in your situation.

Related