java - 定义的静态变量计数

时间:2014-03-06 21:40:30

标签: java variables static

我对java有点新,我想知道是否可以检索已使用特定名称定义的静态变量的数量?例如:

public static final String DB_CTRLDATA              = "controldata";
public static final String DB_CTRLDATA_CELLADDR     = DB_CTRLDATA  + ".cell_addr";
public static final String DB_CTRLDATA_ID           = DB_CTRLDATA  + ".id";
public static final String DB_CTRLDATA_PRICT        = DB_CTRLDATA  + ".pri_count";
public static final String DB_CTRLDATA_RMODE        = DB_CTRLDATA  + ".rmode";
public static final String DB_CTRLDATA_TOD          = DB_CTRLDATA  + ".tod";
public static final String DB_DWELLDATA             = "dwelldata";
public static final String DB_DWELLDATA_FILENAME    = DB_DWELLDATA + ".filename";
public static final String DB_DWELLDATA_ID          = DB_DWELLDATA + ".id";
public static final String DB_DWELLDATA_OFFSET      = DB_DWELLDATA + ".offset";
public static final String DB_DWELLDATA_SIZE        = DB_DWELLDATA + ".size";
public static final String DB_POSTPROC              = "postproc";
public static final String DB_POSTPROC_ID           = DB_POSTPROC  + ".id";
public static final String DB_POSTPROC_PRESENT      = DB_POSTPROC  + ".present";

我想知道用名称DB_ *定义了多少个对象。我知道将所有这些放在一个数组中就是一个解决方案。

谢谢!

2 个答案:

答案 0 :(得分:5)

您可以使用反射来执行此操作。您可以使用Class.getDeclaredFields()方法访问类中定义的所有字段。然后,您可以使用Field.getModifiers()Modifier.isStatic(int)迭代这些字段并检查其修改器。如果字段为static,则可以检查其名称uisng Field.getName()。一个简短的例子:

int count = 0;
for (Field field : MyClassName.class.getDeclaredFields()) {
    int modifiers = field.getModifiers();
    if (Modifier.isStatic(modifiers)) {
        if (field.getName().startsWith("DB_")) {
            count++;
        }
    }
}

请注意,您必须处理SecurityException引发的Class.getDeclaredFields()

答案 1 :(得分:0)

我认为更好的方法是使用枚举然后反思。反射是“一点点”慢^^。在生产中你不会有SecurityException:)

 public Example() {

        DB[] aliases = DB.values();
        aliases[0].getAlias();
    }

    public static final String DB_CTRLDATA              = "controldata";
    public enum DB{

        CTRLDATA("controldata"),
        CTRLDATA_CELLADDR(DB_CTRLDATA + ".cell_addr");

        private String alias;
        public String getAlias() {
            return alias;
        }
        public void setAlias(String alias) {
            this.alias = alias;
        }
        private DB(String a){
            a = alias;
        }
    }