【发布时间】:2025-12-04 11:45:02
【问题描述】:
我正在为一种新语言开发一个插件,并且我正在尝试向编译器添加对编译选项的支持。我以org.gradle.api.tasks.compile.CompileOptions 类为起点,实现了我自己的类,如下所示:
class SvCompileOptions extends AbstractOptions {
private List<String> compilerArgs = Lists.newArrayList();
@Input
public List<String> getCompilerArgs() {
return compilerArgs;
}
public void setCompilerArgs(List<String> compilerArgs) {
this.compilerArgs = compilerArgs;
}
}
在我的 build.gradle 文件中,我尝试执行以下操作:
compileSv {
options.compilerArgs += [ "-foo" ]
}
(compileSv 是一个具有 SvCompileOptions 类型的 options 属性的任务。)
我收到以下错误:
A problem occurred evaluating project ':uvc2'.
> java.lang.AbstractMethodError (no error message)
如果我将这一行替换为:
compileSv {
options.compilerArgs.add("-foo")
}
然后一切正常,但不是很渐变。
谁能指出我做错了什么?
根据@tim_yates 的建议,我添加了一个附加到compilerArgs 的函数:
class SvCompileOptions extends AbstractOptions {
void compilerArgs(String... args) {
this.compilerArgs.addAll(args as List)
}
}
根据@Opal 的建议,我创建了一个准系统示例:
// File 'build.gradle'
buildscript {
dependencies {
classpath 'com.google.guava:guava:16+'
}
repositories {
mavenCentral()
}
}
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
class SvCompileOptions extends AbstractOptions {
private List<String> compilerArgs = Lists.newArrayList();
@Input
public List<String> getCompilerArgs() {
return compilerArgs;
}
public void setCompilerArgs(List<String> compilerArgs) {
this.compilerArgs = compilerArgs;
}
void compilerArgs(String... args) {
this.compilerArgs.addAll(args as List)
}
}
class SvCompile extends DefaultTask {
@TaskAction
protected void compile() {
println options.compilerArgs
}
@Nested
SvCompileOptions options = new SvCompileOptions()
}
task compileSv(type: SvCompile)
compileSv {
options.compilerArgs 'foo', 'bar'
}
代码将参数附加到空列表并按预期打印[foo, bar]。如果我们尝试使用以下内容覆盖参数:
compileSv {
options.compilerArgs = ['one', 'two']
}
打印一条错误消息:
* What went wrong:
A problem occurred evaluating root project 'so_compile_options2'.
> SvCompileOptions.setProperty(Ljava/lang/String;Ljava/lang/Object;)V
我不确定为什么在build.gradle 中内联类时错误消息会有所不同,但我认为这是导致我看到的AbstractMethodError 的原因。
正如@Opal 所指出的,这个问题是由AbstractOptions 类中的一些魔法引起的。我尝试将以下方法添加到编译选项类中,但错误消息仍然存在:
class SvCompileOptions extends AbstractOptions {
private static final ImmutableSet<String> EXCLUDE_FROM_ANT_PROPERTIES =
ImmutableSet.of("compilerArgs");
@Override
protected boolean excludeFromAntProperties(String fieldName) {
return EXCLUDE_FROM_ANT_PROPERTIES.contains(fieldName);
}
// ...
}
exclude 函数似乎根本没有被调用,就好像我在其中添加了一个虚拟打印它永远不会发出一样。
【问题讨论】:
-
您能提供一个SSCCE吗?并使用
-s开关运行脚本? -
如果你不扩展
AbstractOptions它会按预期工作,所以我猜这门课引入了一些 magic - 现在不能帮助你 - 必须做我的自己的工作。 -
@Opal 感谢有关
AbstractOptions的提示。 SSCCE 是什么意思? -
这只是一个工作示例:sscce.org :)
-
@Opal 我很遗憾没有提供示例,但是当我发布问题时我没有可用的代码/基础设施。我希望这是一个简单的问题,有经验的 Gradle 用户可以立即发现。我稍后会更新问题。
标签: gradle groovy gradle-plugin