我如何计算为 Java 类定义的 int 成员的数量? [英] How might I count the number of int members defined for a Java class?

查看:76
本文介绍了我如何计算为 Java 类定义的 int 成员的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类存储了大量的int成员变量,每个成员变量定义如下:

I have a class that stores a large number of int member variables, each defined as follows:

public final static int int1 = int1value;
public final static int int2 = int2value;
...
public final static int int106 = int106value;

有第二个类需要根据第一个类中int的数量做一个循环.我将如何向第一个类添加一个函数来计算这些成员变量?

There is a second class that needs to do a loop based on the number of ints in the first class. How would I go about adding a function to the first class to count these member variables?

推荐答案

第一类中只有 106 个public final static int int1 = int1value".没有列表或数组.

It's just 106 "public final static int int1 = int1value" in the first class. No List or Arrays.

好蹩脚!

不幸的是,没有一种巧妙的方法可以对大量静力学的值求和.您可以使用反射来实现(参见@BalusC 的回答),或者简单地通过编写一个方法来计算硬接线表达式,例如:

Unfortunately there is no neat way to sum the values of a large number of statics. You could do it using reflection (see @BalusC's answer), or simply by writing a method evaluates hard-wired expressions like:

public static int calculateSum() {
    return int1 + int2 + 
           // and so on
           + int160;
}

public static int calculateCount() {
    return 160;
}

您真正的问题在于您的程序设计.静态的使用是可疑的,使用 160 个命名变量(而不是数组或列表)是不好的,甚至将方法放在单独的类中也是可疑的.

Your real problem is in your program design. The use of statics is dubious, the use of 160 named variables (instead of an array or list) is bad, and even putting the method(s) in a separate class is dubious.

解决设计问题,而您没有这个问题.

Fix the design problems and you don't have this one.

这篇关于我如何计算为 Java 类定义的 int 成员的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆