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

Eclipse JDT ListRewrite插入新节点位置错误问题

Eclipse JDT批处理模式下ListRewrite插入注解位置错误问题

我最近捣鼓了个独立项目,想靠Eclipse JDT框架做个批处理工具,给代码里部分选中的字段自动加注解——不是做Eclipse插件形式,是把所有需要的依赖都塞进项目里,直接以批处理模式运行。结果踩了个坑:ListRewrite没能把注解插入到正确的位置。

我的处理逻辑是先通过AST访问器把所有字段声明都存入一个映射表,再逐一取出字段进行处理,相关核心代码片段如下:

// 先通过访问器收集所有字段声明到映射表
Map<String, FieldDeclaration> fieldDeclarationMap = new HashMap<>();
// ... 省略通过ASTVisitor遍历收集字段的逻辑

// 遍历映射表,逐个处理字段
FieldDeclaration fld = lVrblDet.listS...; // 此处为获取目标字段的代码片段

// 尝试用ListRewrite插入注解
ASTRewrite rewrite = ASTRewrite.create(fld.getAST());
ListRewrite listRewrite = rewrite.getListRewrite(fld.getParent(), TypeDeclaration.BODY_DECLARATIONS_PROPERTY);

// 创建要添加的注解节点
MarkerAnnotation targetAnnotation = fld.getAST().newMarkerAnnotation();
targetAnnotation.setTypeName(fld.getAST().newName("MyTargetAnnotation"));

// 尝试将注解插入到字段前方
listRewrite.insertBefore(targetAnnotation, fld, null);

目前的问题是,执行这段代码后,注解并没有出现在预期的字段上方位置,而是跑到了其他奇怪的地方,有没有大佬能帮忙看看哪里出问题了?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:06:28