How to get the number of attributes in java class?

I have a java class containing all columns of a database table as attributes (member variables) and corresponding getters and setters.

I want to have a method in this class with a name getColumnCount()that returns the number of columns (i.e. the number of attributes in the class)? How to implement this without hard number coding? I am open to critics about this in general and suggestions. Thank.

+5
source share
3 answers

Check reflection API . If the class in question is actually pure javabei, you can get the number of fields (properties or columns, as you call it) as follows:

public int getColumnCount() {
    return getClass().getDeclaredFields().length;
}

, , . , , /, .

+18

, "^set.+$".

0

, "DatabaseColumn", , . getter. , .

// in this sample annotation used for getter methods
public int getColumnCount() {
    int count = 0;
    Method[] methods = getClass().getDeclaredMethods(); 
    for (Method method : methods) {
        if (method.isAnnotationPresent(DatabaseColumn.class)) {
            count++;
        }
    }
    return count;
}
0

All Articles