txcotrader
txcotrader

Reputation: 595

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!

Upvotes: 3

Views: 468

Answers (2)

s7474
s7474

Reputation: 58

I think that better way is using enum then reflection. Reflection is a "little bit" slower ^^. And on production u won't have 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;
        }
    }

Upvotes: 0

Robin Krahl
Robin Krahl

Reputation: 5308

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().

Upvotes: 5

Related Questions