简体   繁体   English

Gradle自定义插件:读取编译的Java类

[英]Gradle Custom Plugins: Read Compiled Java Class

In a custom plugin (or task) I would like to read all compiled classes (preferrably those that have changed from last compilation) with a classloader so that I'll be able to use reflection on them. 在自定义插件(或任务)中,我想使用类加载器读取所有已编译的类(最好是自上次编译以来已更改的类),以便能够对它们进行反射。

Is that possible? 那可能吗?

1) It would be great to have a cook right after a Java class was compiled so that I could read it, but I found no way to do this. 1)在编译Java类之后立即做饭是一件很棒的事,以便我可以读取它,但是我发现没有办法这样做。

2) I'm thinking of something like this ... 2)我在想这样的事情...

compileJava.doLast {
    ClassLoader parent = getClass().getClassLoader();
    GroovyClassLoader loader = new GroovyClassLoader(parent);


    // retrieve all class files
    // for each class file, loader.parseClass(classFile)
}

In a gradle script getClass().getClassloader() will get you the classloader of the gradle script. 在gradle脚本中, getClass().getClassloader()将为您提供gradle脚本的类加载器。 This will NOT contain the compiled classes or compile/runtime jars. 这将不包含已编译的类或编译/运行时jar。 I think you want to do something similar to: 我认为您想做类似的事情:

Collection<URL> urls = sourceSets.main.runtimeClasspath.files.collect { it.toURI().toURL() }
Classloader parent = new URLClassLoader(urls.toArray());

If you want to only act on the classes that have changed you are best to do do that in an incremental task 如果只想对已更改的类执行操作,则最好在增量任务中执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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