即使从 class 中删除节点后,ClassOrInterfaceDeclaration.getTokenRange() 仍会获取文件的所有标记

ClassOrInterfaceDeclaration.getTokenRange() gets all the tokens for a file even after removing nodes from the class

当我从包含多个 class 的解析文件中的 CompilationUnit (JavaParser) 的 class 中删除“ClassOrInterfaceDeclaration”节点时,ClassOrInterfaceDeclaration.getTokenRange() 获取所有标记甚至删除的节点令牌。 例如,位置 1 和 2 的代码片段将给出相同的结果,尽管我已经从 ClassOrInterfaceDeclaration n.

中删除了节点

有谁知道如何获得正确的令牌列表?

private void RemoveOtherClassesFromSameFile(ClassOrInterfaceDeclaration n) {
     n.getTokenRange() // 1
    List<ClassOrInterfaceDeclaration> internalClasses = unmodifiableList(
            n.getMembers().stream().filter(m -> m instanceof ClassOrInterfaceDeclaration)
                    .map(m -> (ClassOrInterfaceDeclaration) m).collect(toList()));
    for (ClassOrInterfaceDeclaration c : internalClasses)
        n.remove(c);
   n.getTokenRange() // 2
}

在调整包含节点的文件之后,您必须使用方法 saveAll 更新源根目录,以将 AST 覆盖到您的文件中,就像那样

sourceRoot.saveAll(Paths.get(parsedFilePath));

完整示例:

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.visitor.ModifierVisitor;
import com.github.javaparser.ast.visitor.Visitable;
import com.github.javaparser.utils.SourceRoot;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public  static  void main(String[] args) throws IOException {
        Path dirPath =  Paths.get("C:\JavaParserTest\src\main\resources\src\");
        SourceRoot sourceRoot = new SourceRoot(dirPath);
        sourceRoot.tryToParse();
        CompilationUnit cu = sourceRoot.parse("", dirPath.toString()+"\JavaFile.java");

        cu.accept(new ModifierVisitor<Void>() {
            @Override
            public Visitable visit(ClassOrInterfaceDeclaration n, Void arg) {
                RemoveOtherClassesFromSameFile(n, cu);
                return super.visit(n, arg);
            }
        }, null);

        sourceRoot.saveAll(Paths.get(dirPath.toString()+"\JavaFile.java"));
    }

    private static ClassOrInterfaceDeclaration RemoveOtherClassesFromSameFile(ClassOrInterfaceDeclaration n, CompilationUnit cu) {
        List<ClassOrInterfaceDeclaration> internalClasses = (
                n.getMembers().stream().filter(m -> m instanceof ClassOrInterfaceDeclaration)
                        .map(m -> (ClassOrInterfaceDeclaration) m).collect(Collectors.toList()));
        for (ClassOrInterfaceDeclaration c : internalClasses){
            n.remove(c);
        }
        return n;
    }

}