【问题标题】:How can I create a ClassLoader from a custom configuration in gradle?如何从 gradle 中的自定义配置创建 ClassLoader?
【发布时间】:2015-06-08 11:54:36
【问题描述】:

我已经定义了一个自定义配置和依赖项。

repositories {
    mavenCentral()
}
configurations {
    myConfig
}
dependencies {
    myConfig   'org.foo:foo:+'
}

如何创建 ClassLoader 来动态加载类?

task myTask {
    def classLoader = configurations.myConfig.????
    def foo = Class.forName( "org.foo.Foo", true, classLoader ).newInstance();
}

【问题讨论】:

  • 你想在这里完成什么?您想将类动态加载到您的 Gradle 构建脚本中吗?为什么?您不能只使用常规的buildscript 块来配置构建脚本的类路径吗?
  • @Jolta 这些类仅用于一些可选任务。对于默认构建,必须 100% 确定没有依赖关系。我使用了额外的配置。

标签: class configuration gradle dependencies classloader


【解决方案1】:

我现在找到了这个解决方案。我希望有更好的解决方案。

def classLoader = getClassLoader( configurations.myConfig )

ClassLoader getClassLoader( Configuration config ) {
    ArrayList urls = new ArrayList()
    config.files.each { File file ->
        urls += file.toURI().toURL()
    }
    return new URLClassLoader( urls.toArray(new URL[0]) );
}

【讨论】:

  • 虽然这是 URLClassLoader 的用途,但您可能想要直接将依赖项添加到您的 buildscript 类路径中。请看下面我的回答。此外,如果您希望从外部类加载器创建的对象共享父加载类型,则绝对应该考虑添加父类加载器。
  • 因为我们还想检查列表中是否缺少依赖项,所以父类加载器是个坏主意。
  • Groovyfication:new URLClassLoader(config.files*.toURI()*.toURL() as URL[])
【解决方案2】:

将您的配置移动到buildscript { dependencies { classpath 'deps:go:here' } }。然后这些类都会自动/正确地添加到 gradle 类路径中(因此您可以在其中引用类型)。

这是将类添加到类路径的“官方”方式。创建任意对象请注意,您只能在 gradle 脚本的最顶部配置 buildscript {}。

如果它是您希望 gradle 构建中所有项目的依赖项,您可以创建一个 buildSrc/build.gradle,您只需将依赖项添加到运行时/实现/编译类路径:dependencies { implementation 'deps:go:here' }

【讨论】:

  • 这不会动态工作。例如,如果您需要在不同的配置中为不同的类加载器提供同一类的不同版本,这将失败。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-31
  • 2011-05-05
  • 2011-02-26
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
相关资源
最近更新 更多