Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - static variable count defined

I'm somewhat new to java and I was wondering if it's possible to retrieve the number of static variables that have been defined with a particular name? For instance:

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";

I'd like to know how many objects have been defined with the name DB_*. I understand putting all of this in an array is a solution.

Thanks!

like image 619
txcotrader Avatar asked Jun 12 '26 13:06

txcotrader


1 Answers

You can use reflection to do this. You can access all fields defined in a class using the Class.getDeclaredFields() method. Then you can iterate over these fields and check their modifiers using Field.getModifiers() and Modifier.isStatic(int). If a field is static, you can check its name uisng Field.getName(). A short example:

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

Note that you will have to handle the SecurityException thrown by Class.getDeclaredFields().

like image 176
Robin Krahl Avatar answered Jun 14 '26 03:06

Robin Krahl