为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Spoon 从 java 类中删除注释?

如何使用 Spoon 从 java 类中删除注释?

人到中年有点甜 2023-06-28 16:17:00
我正在使用SequenceR来解析我的 Java 代码文件。它使用SpoonJava库,这是一个流行的代码分析库。我需要的是,我将向分析器提供一个有错误的行号,它将检测该行并找出它的方法或类,并将删除该类或方法上的所有注释。我尝试了多种方法来实现这一目标。但无法真正得到想要的输出。这是我的输入 Java 文件。我在分析器代码中所做的是这样的 -    public static void generateAbstraction(File buggy_file, int buggy_line, File working_dir) {        Launcher launcher = new Launcher();        launcher.getEnvironment().setAutoImports(true);        launcher.getEnvironment().setNoClasspath(true);        launcher.getEnvironment().setCommentEnabled(true);        launcher.addInputResource(buggy_file.toString());        try {            launcher.buildModel();        } catch (Exception e) {        }        CtModel model = launcher.getModel();        CtMethod topLevelmethod = null;        CtElement buggy_ctElement = null;        CtElement tmp_ctElement = null;        CtPath buggy_ctElement_ctPath = null;        // This is the main part        for (CtType<?> ctType : model.getAllTypes()) {            for (Iterator<CtElement> desIter = ctType.descendantIterator(); desIter.hasNext(); ) {                tmp_ctElement = desIter.next();                try {                    // Main problem resides here                    if (tmp_ctElement.getPosition().getLine() == buggy_line && !(tmp_ctElement instanceof CtComment)) {                        buggy_ctElement = tmp_ctElement;                        buggy_ctElement_ctPath = tmp_ctElement.getPath();                        topLevelmethod = getTopLevelMethod(buggy_ctElement);                        List<CtComment> comments = topLevelmethod.getElements(                                new TypeFilter<CtComment>(CtComment.class)                        );                        for(CtComment c: comments){                               topLevelmethod.removeComment(c);                        }                        break;                    }仔细一看,你会发现只有一条评论被删除了。那是 -/* uses badsource and badsink */其他评论完好无损。但我需要删除类或方法中的所有注释。我究竟做错了什么?我对勺子完全陌生。任何帮助,将不胜感激。
查看完整描述

1 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

要删除文件的所有注释,您只需关闭一个标志即可。

这条线发挥了魔力——

launcher.getEnvironment().setCommentEnabled(false);

它的作用是,它设置setCommentEnabledfalse并且注释被完全忽略。所以,你根本不需要担心它们。

查看完整回答
反对 回复 2023-06-28
  • 1 回答
  • 0 关注
  • 305 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号