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

StaticJavaParser解析FQ类型名称出现异常行为的问题咨询

问题解答

这是预期行为吗?

是的,这属于JavaParser AST(抽象语法树)结构的正常设计。全限定类名在AST中是分层存储的:

  • java.lang.String 是一个 ClassOrInterfaceType 节点,它的scope属性指向java.lang节点
  • java.lang 本身也是一个 ClassOrInterfaceType 节点,它的scope属性指向java节点
  • java 同样是一个独立的 ClassOrInterfaceType 节点

当你遍历整个CompilationUnit的所有节点时,这些分层的节点都会被匹配到,所以会输出三个结果。

如何过滤冗余元素?

你需要过滤掉那些作为其他ClassOrInterfaceType节点的scope存在的元素。核心逻辑是:检查当前节点是否是某个父级ClassOrInterfaceType节点的scope,如果是则跳过,否则保留。

修改后的代码示例:

CompilationUnit cu = StaticJavaParser.parse(
  "public class foo extends java.lang.String {};");
cu.stream()
  .filter(ClassOrInterfaceType.class::isInstance)
  .map(ClassOrInterfaceType.class::cast)
  .filter(type -> {
      Optional<Node> parent = type.getParentNode();
      if (parent.isEmpty()) {
          return true;
      }
      if (!(parent.get() instanceof ClassOrInterfaceType)) {
          return true;
      }
      ClassOrInterfaceType parentType = (ClassOrInterfaceType) parent.get();
      return parentType.getScope().isEmpty() || !parentType.getScope().get().equals(type);
  })
  .forEach(System.out::println);

运行这段代码后,只会输出java.lang.String,符合你的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:20:41