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

如何统计Java类中定义的String类型成员变量总数

问题描述

现有一个定义了多个String类型成员变量的Java类,需要统计该类中所有String类型成员变量的总数量,示例Account类代码如下:

public class Account {
    
    //objects
//    private String pageAuthenticationNavBar = "xpath:=//div[@class='ng-binding' and contains(text(),'Account Authentication')]";
    private String listAuthMethod = "id:=account-authentication-authentication-methods";
    private String btnContinue = "xpath:=//button[@id='account-authentication-continue']";
    private String btnSkip = "xpath:=//*[contains(text(), 'Send OTP')]/..//*[contains(text(),'Skip')]";
    private String btnSkipNoSMS = "xpath:=//*[@class='skip-sms-auth-container']//*[contains(text(),'Skip Authentication')]";
    private String formAccountAuthentication = "xpath:=//*[@class='global-container authentication-process']";
    private String txtChooseSubscriber = "xpath:=//div[contains(text(), 'Choose Subscriber')]";
    private String txtSubscriberByIndex = "xpath:=(//*[contains(@class,'flex subscriber-item-inside-list')]//*[@class='subscriber-icon'])[INDEX]";
    private String btnSendOtp = "xpath:=//button[starts-with(@class,'auth-continue-button')]"; //id:=account-authentication-send-otp
    private String txtOtp = "id:=smsCodeInput";
}

有多种可行方案可以实现该需求,可根据实际使用场景选择:

可行实现方案

1. 反射运行时统计(通用性最高)

直接通过Java原生反射机制读取类的声明字段,过滤String类型完成统计,示例代码:

import java.lang.reflect.Field;

public class StringFieldCounter {
    public static int countStringFields(Class<?> targetClass) {
        int count = 0;
        // 遍历当前类所有声明的成员变量
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.getType() == String.class) {
                count++;
            }
        }
        // 如需统计父类的String字段,放开下面这段递归逻辑即可
        // Class<?> superClass = targetClass.getSuperclass();
        // if (superClass != null && superClass != Object.class) {
        //     count += countStringFields(superClass);
        // }
        return count;
    }

    public static void main(String[] args) {
        int total = countStringFields(Account.class);
        System.out.println("String类型成员变量总数:" + total);
        // 针对给出的Account示例类,输出结果为9,自动排除了注释掉的字段
    }
}

注意:如果目标类做了字节码加密、或者配置了安全管理器禁止反射访问字段,该方案会失效,常规业务场景不受影响。

2. 源码正则匹配统计(无需运行代码)

如果只是快速统计源码文件中的字段数,不需要启动程序,可以直接用正则匹配.java源文件内容:

  • 匹配规则:^\s*(private|public|protected)\s+String\s+\w+\s*=
  • 统计时跳过//开头的注释行即可,给出的Account示例类用该规则匹配结果同样为9。
  • 如果使用IntelliJ IDEA,直接打开类文件按Ctrl+F勾选正则模式,输入上述规则,搜索结果条数就是统计值。

3. 编译期注解处理器(适合项目长期使用)

如果需要在项目中常态化做字段统计、甚至做字段数量合规校验,可以自定义JSR-269规范的注解处理器,在代码编译阶段扫描所有类的String字段,自动输出统计结果:

  • 没有运行时性能损耗
  • 可以自定义排除规则、生成统计报表
  • 适合团队统一规范校验场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 11:24:15