[英]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: 然后我决定尝试一下compileJava:
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. 我想获取文件的Class对象。
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. 因此,例如,如果我有com.example.SomeClass
,我希望得到Class<com.example.SomeClass>
以便可以在这些类上使用反射。
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 PS:我正在使用Gradle 2.5和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 这是我设法得到的,虽然不是很漂亮,但它确实完成了获取Class对象的工作
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. 它创建一个新的类加载器,添加默认的输出类dir,以及compile
配置中的所有依赖类,然后从classesDir构建文件列表,将它们从路径转换为格式为'abYourClass'的字符串,然后加载它进入并转储类上的方法。
You can add your own logic for what attributes from the methods you need, but this should get you going. 您可以为需要的方法中的属性添加自己的逻辑,但这应该可以助您一臂之力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.