无构建工具插件运行OpenRewrite时RunRewriteManually编译报错求助
问题场景
按照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: Listcannot be converted to LargeSourceSet
Listresults = 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 methodtoList()
错误原因
javaParser.parse()返回的是Stream<SourceFile>,SourceFile是CompilationUnit的父类,无法直接将父类集合转换为子类集合,导致类型推断失败。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

