You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无构建工具插件运行OpenRewrite时RunRewriteManually编译报错求助

OpenRewrite手动运行代码编译错误解决

问题场景

按照OpenRewrite官方文档中「无需构建工具插件运行Rewrite」的指引编写手动运行类,但代码编译失败,出现以下两类错误:

直接编译时的错误

.../src/main/java/com/wamas/core/rewrite/Rewrite.java:49: error: incompatible types: Stream cannot be converted to List
List<J.CompilationUnit> cus = javaParser.parse(sourcePaths, projectDir, ctx);
^
.../src/main/java/com/wamas/core/rewrite/Rewrite.java:53: error: incompatible types: List cannot be converted to LargeSourceSet
List results = recipe.run(cus, ctx).getResults();
^

添加.collect(Collectors.toList())后的错误

/src/main/java/com/wamas/core/rewrite/Rewrite.java:50: error: incompatible types: inference variable T has incompatible bounds
List<J.CompilationUnit> cus = javaParser.parse(sourcePaths, projectDir, ctx).collect(Collectors.toList());
^
equality constraints: CompilationUnit
lower bounds: SourceFile
where T is a type-variable:
T extends Object declared in method toList()

错误原因

  1. javaParser.parse()返回的是Stream<SourceFile>,SourceFile是CompilationUnit的父类,无法直接将父类集合转换为子类集合,导致类型推断失败。
  2. recipe.run()方法要求的参数类型是LargeSourceSet,而非普通的List<CompilationUnit>,这是第二个类型不兼容错误的核心原因。

解决方案

1. 正确转换解析结果类型

在收集解析结果时,先过滤出CompilationUnit类型的元素并强制转换:

import java.util.stream.Collectors;
// ...
List<J.CompilationUnit> cus = javaParser.parse(sourcePaths, projectDir, ctx)
    .filter(J.CompilationUnit.class::isInstance)
    .map(J.CompilationUnit.class::cast)
    .collect(Collectors.toList());

2. 构建符合要求的LargeSourceSet

使用OpenRewrite提供的InMemoryLargeSourceSet将List<CompilationUnit>包装为LargeSourceSet:

import org.openrewrite.java.InMemoryLargeSourceSet;
// ...
LargeSourceSet sourceSet = new InMemoryLargeSourceSet(cus);
List<Result> results = recipe.run(sourceSet, ctx).getResults();

3. 校验依赖版本一致性

确保项目中rewrite-core、rewrite-java等核心依赖的版本与文档版本一致,版本差异可能导致方法签名不匹配。

内容的提问来源于stack exchange,提问作者didierX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:02:22