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.
解决方案
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.