简体   繁体   中英

How to use application classpath in Gradle task

The idea is rather simple, I want to access project classes in my build script directly.

I first tried:

apply plugin: 'java'

tasks.create(name: 'randomTask', type: SourceTask) {
    source.each {
        println it
    }
}

and sadly got exactly zero files.

Then i decided to give compileJava a try:

apply plugin: 'java'

compileJava {
    source.each {
        println it
    }
}

and while indeed I did get a list of files that will be compiled it's not really what I need. I want to get the Class objects of the files.

So for example if I had com.example.SomeClass , I'd expect to get Class<com.example.SomeClass> so that I could use reflections on those classes.

Here's a non-working example of what I'd like:

apply plugin: 'java'

tasks.create(name: 'randomTask', type: SomeMagicalType) {
    UMLBuilder builder = UMLBuilder.builder()
    classes.each { clazz ->
        clazz.methods.each { method ->
            builder.addMethod(method)
        }
    }
    builder.build().writeToFile(file('out/application.uml'))
}

PS: I'm using Gradle 2.5 and Java 8

I had a little play trying to get the classes in a project and instantiating them. This is what I managed to get, it's not pretty but it does the raw job of getting the Class object

task allMethods(dependsOn: classes) << {
    def ncl = new GroovyClassLoader()
    ncl.addClasspath("${sourceSets.main.output.classesDir}")
    configurations.compile.each { ncl.addClasspath(it.path) }
    def cTree = fileTree(dir: sourceSets.main.output.classesDir)
    def cFiles = cTree.matching {
        include '**/*.class'
        exclude '**/*$*.class'
    }
    cFiles.each { f ->
        def c = f.path - (sourceSets.main.output.classesDir.path + "/")
        def cname = c.replaceAll('/', '\\.') - ".class"
        def cz = Class.forName(cname, false, ncl)
        cz.methods.each { println it }
    }
}

It creates a new class loader, adds the default output classes dir, and all dependency classes from the compile configuration, then builds a list of files from the classesDir, converts them from a path to a string in format 'abYourClass', and then loads it in and dumps out the methods on the classes.

You can add your own logic for what attributes from the methods you need, but this should get you going.

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