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

JavaParser解析时在ClassDeclaration中无法找到字段级@Setter注解求助

问题解答

1. @Setter的位置

字段上的@Setter属于类的字段成员,而非类本身的注解。你需要遍历类的成员列表,定位到对应的FieldDeclaration节点,再从该节点获取注解:

  • 你之前调用classDecl.getMembers().get(0)拿到的是构造方法public A(),这个成员本身没有注解,所以返回空列表。
  • 正确的做法是遍历classDecl.getMembers(),筛选出FieldDeclaration类型的成员,再调用field.getAnnotations()或field.getLeadingAnnotations()获取字段上的@Setter。

示例代码:

@Override
public Void visitClassDeclaration(ClassDeclaration classDecl, Void arg) {
    // 遍历类成员,查找字段上的@Setter
    for (BodyDeclaration<?> member : classDecl.getMembers()) {
        if (member instanceof FieldDeclaration field) {
            for (AnnotationExpr annotation : field.getLeadingAnnotations()) {
                if ("Setter".equals(annotation.getName().getIdentifier())) {
                    // 成功定位到字段上的@Setter
                    System.out.println("找到@Setter注解,所属字段:" + field.getVariables().get(0).getName());
                }
            }
        }
    }
    return super.visitClassDeclaration(classDecl, arg);
}

2. 为什么classDecl.type下的注解为空或null

classDecl.type对应的是类的类型引用节点(ClassOrInterfaceType),这个节点仅负责存储类的名称信息,不持有类的注解、成员列表等数据:

  • classDecl.type.getAnnotations()返回null是正常行为,因为类型引用节点本身不会存储注解。
  • classDecl.type.getMembers()是错误的调用,类型引用节点没有成员列表,类的成员列表需要通过classDecl.getMembers()获取。

类本身的注解存储在ClassDeclaration节点本身(classDecl.getAnnotations()/classDecl.getLeadingAnnotations()),成员的注解则分别存储在对应的成员节点(如FieldDeclaration、ConstructorDeclaration)中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:00:08