views:

95

answers:

3

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

I want to have a method in this class called getColumnCount() that returns the number of columns (i.e. the number of attributes in the class)? How would I implement this without hardcoding the number? I am open to critisims on this in general and suggestions. Thanks.

+3  A: 

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

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

I however highly question the need for this. If you elaborate a bit more about the functional requirement for which you think that you need this approach/solution, then we may be able to suggest better ways.

BalusC
Thanks, this works. As far as the reasoning, it is mainly for logging: I need to know the number of columns in the table so that I may keep track of old<->new data in the fields during updates. The column count is necessary so the logging classes know how many rows to insert into loggin table.
llm
If you're using a decent ORM API, you can use the API-provided methods to figure the mapping details. JPA and good ol' Hibernate can do that.
BalusC
Yes. Unfortunately the code I am working with does not use an ORM API.
llm
OK, you're welcome and good luck with the code. If you have more questions, you know to find us.
BalusC
A: 

One approach would be to use reflection to list the methods of the class and count the methods whose name match the regular expression "^set.+$".

maerics
A: 

Make an annotation like "DatabaseColumn", use it which fields map to a table column. You can use annotation for fields or getter methods. so it is safe for transient fields for not used in database table.

// 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;
}
Black Eagle