如何从 gradle 中的自定义配置创建 ClassLoader?
How can I create a ClassLoader from a custom configuration in gradle?
我已经定义了自定义配置和依赖项。
repositories {
mavenCentral()
}
configurations {
myConfig
}
dependencies {
myConfig 'org.foo:foo:+'
}
如何创建 ClassLoader 以动态加载 class?
task myTask {
def classLoader = configurations.myConfig.????
def foo = Class.forName( "org.foo.Foo", true, classLoader ).newInstance();
}
我现在找到了这个解决方案。我希望有更好的解决方案。
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]) );
}
将您的配置移至 buildscript { dependencies { classpath 'deps:go:here' } }
。然后 类 全部自动/正确添加到 gradle 类路径(因此您可以在其中引用类型)。
这是将 类 添加到类路径的 "official" 方法。创建任意对象 请注意,您只能在 gradle 脚本的最顶部配置 buildscript {}。
如果您希望在 gradle 构建中的所有项目中建立依赖关系,您可以创建一个 buildSrc/build.gradle
,您只需将依赖关系添加到 runtime/implementation/compile 类路径:dependencies { implementation 'deps:go:here' }
.
我已经定义了自定义配置和依赖项。
repositories {
mavenCentral()
}
configurations {
myConfig
}
dependencies {
myConfig 'org.foo:foo:+'
}
如何创建 ClassLoader 以动态加载 class?
task myTask {
def classLoader = configurations.myConfig.????
def foo = Class.forName( "org.foo.Foo", true, classLoader ).newInstance();
}
我现在找到了这个解决方案。我希望有更好的解决方案。
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]) );
}
将您的配置移至 buildscript { dependencies { classpath 'deps:go:here' } }
。然后 类 全部自动/正确添加到 gradle 类路径(因此您可以在其中引用类型)。
这是将 类 添加到类路径的 "official" 方法。创建任意对象 请注意,您只能在 gradle 脚本的最顶部配置 buildscript {}。
如果您希望在 gradle 构建中的所有项目中建立依赖关系,您可以创建一个 buildSrc/build.gradle
,您只需将依赖关系添加到 runtime/implementation/compile 类路径:dependencies { implementation 'deps:go:here' }
.