简体   繁体   中英

How to create JAR from specific classes and use it with Gradle?

I have few Java classes that I want to use on different projects.

I don't want to move these classes in a dedicated project for now.

So I want to build a JAR with these classes, and be able to use it in my other projects, all with Gradle.

So here my JAR task (sources) and I publish it as an artifact :

task utilitiesJar(type: Jar) {
    baseName = 'utilities'
    version =  '0.0.1'
    includeEmptyDirs = false
    from sourceSets.main.allJava
    include "**\\common\\exceptions\\**"
    include "**\\common\\json\\**"
    include "**\\common\\logging\\**"
}

publishing {
    publications {
        utilities(MavenPublication) {
            artifact utilitiesJar
            groupId group
            artifactId utilitiesJar.baseName
            version utilitiesJar.version
        }
    }
    repositories {
        maven {
            url 'my_URL'
        }
    }
}

I get it back with an other project :

repositories {
    mavenCentral()

    maven {
        url 'my_URL'
    }
}

...
compile (...)
...

Seems like the JAR is correctly imported (I can see it in "External Libraries" of IntelliJ, with all its classes), but I can't use it. Maybe because the .class files are missing ? I'm beginner in Java, maybe I missed something.

How can I create a JAR with only some classes and then use it ?

Ok so as said in comments, I have to include the builded .class files, I can't use external .java classes like this.

So my solution :

def utilitiesName = '...'
def utilitiesVersion = '0.0.1'

task utilitiesJar(type: Jar, dependsOn: classes) {
    baseName = utilitiesName
    version =  utilitiesVersion
    includeEmptyDirs = false
    from sourceSets.main.output
    include ("**\\common\\exceptions\\**\\*", "**\\common\\json\\**\\*", "**\\common\\logging\\**\\*")
}

task utilitiesSourcesJar(type: Jar, dependsOn: classes) {
    baseName = utilitiesName
    version =  utilitiesVersion
    classifier = 'sources'
    includeEmptyDirs = false
    from sourceSets.main.allJava
    include ("**\\common\\exceptions\\**\\*", "**\\common\\json\\**\\*", "**\\common\\logging\\**\\*")
}

publishing {
    publications {
        utilities(MavenPublication) {
            artifact utilitiesJar
            artifact utilitiesSourcesJar
            groupId group
            artifactId utilitiesName
            version utilitiesVersion
        }
    }
    repositories {
        maven {
            url 'myURL'
        }
    }
}

Now I can use it and see the classes in my IDE.

PS : doing in this way is pretty dirty. Create a sub-project / a module, it's just the way how to do it, that's finaly what I did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM