在 Gradle 构建脚本中使用 Java 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26314709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Java class in Gradle build script
提问by WeSt
I have a Gradle build script which has to instantiate a Java class in a Task and call a method on the created object. Currently, I have the following:
我有一个 Gradle 构建脚本,它必须在 Task 中实例化一个 Java 类并在创建的对象上调用一个方法。目前,我有以下几点:
apply plugin: 'java'
dependencies {
compile files("libs/some.library.jar")
}
task A << {
def obj = new some.library.TestClass()
obj.doSomething()
}
The problem is that the class some.library.TestClass()
is not found. I read this articleabout how to use Groovy classes in Gradle, but I need my Java class to come from an external JAR file. How can I add a jar to the build source? It seems that the dependencies
block doesnt do what I expect it to do. Can anyone give me a hint in the right direction?
问题是some.library.TestClass()
找不到类。我阅读了这篇关于如何在 Gradle 中使用 Groovy 类的文章,但我需要我的 Java 类来自外部 JAR 文件。如何将 jar 添加到构建源?似乎dependencies
块没有做我期望它做的事情。谁能给我一个正确方向的提示?
回答by Opal
The dependency compile files("libs/some.library.jar")
is added as a project dependency not as the script dependency itself. What You need to do is to add this dependency in script's classpath
scope.
该依赖项compile files("libs/some.library.jar")
被添加为项目依赖项,而不是脚本依赖项本身。您需要做的是在脚本的classpath
范围内添加此依赖项。
apply plugin: 'java'
buildscript {
dependencies {
classpath files("libs/some.library.jar")
}
}
task A << {
def obj = new some.library.TestClass()
obj.doSomething()
}
Now it should work.
现在它应该可以工作了。