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!
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With