ReflectionsException:无法获取名称 org.gradle.api.Plugin 的类型

ReflectionsException: Could not get type for name org.gradle.api.Plugin

我已经实现了自定义 Gradle 插件并且它可以工作,但是在 Gradle 构建期间我有一个 ReflectionsException: Could not get the type for name org.gradle.api.Plugin 因为反射扫描。为什么 class 加载程序看不到类型?

Caused by: java.lang.ClassNotFoundException: org.gradle.api.Plugin
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.reflections.ReflectionUtils.forName(ReflectionUtils.java:388)

自定义插件实现 Plugin<Project> 如下所示:

//CommonGradlePlugin
import org.gradle.api.Plugin;
import org.gradle.api.Project; 

public class CommonGradlePlugin implements Plugin<Project> {
    //...
}

Why class loader doesn't see the type?

我想 gradle 类 没有包含在 compile/runtime 类路径中,只是因为它是一个构建工具。这就是反射无法找到gradle 类的原因。

您可以使用 Reflection 的 ConfigurationBuilder 排除带有 gradle 插件的包:

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
FilterBuilder filterBuilder = new FilterBuilder();

configurationBuilder.addUrls(ClasspathHelper.forPackage(PACKAGE_TO_SCAN));
filterBuilder
        .includePackage(PACKAGE_TO_SCAN)
        .excludePackage(PACKAGE_TO_EXCLUDE);
configurationBuilder.filterInputsBy(filterBuilder);

Reflections reflections = new Reflections(configurationBuilder);