How to get number of attributes in a java class?
I have a java class containing all the columns of a database table as attributes (mem开发者_如何学运维ber 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.
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;
}
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.+$
".
I used to have the same purpose as yours, then made a function powered by Java reflection for solving that.
Guess I can help you.
/**
* author: Amo
* to use auto-gen SQL create command to create a table having columns named same as the name of model fields
*/
public void setSQLCreateCmd(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
String fieldName;
Class<?> fieldType;
int fieldCount = fields.length;
Log.d("[DEBUG]", "... fieldCount:" + fieldCount);
int i = 0;
DATABASE_CMD = "create table if not exists " + DATABASE_NAME +
"(" +
"_id integer primary key autoincrement, ";
for (Field field : fields) {
if (!field.isAccessible()) field.setAccessible(true);
fieldName = field.getName();
fieldType = field.getType();
if (fieldName.compareTo("") == 0) {
Logger.d("!!! field name is empty");
continue;
}
if (i == fieldCount - 1) {
Logger.d("... field at " + (i+1) + "named " + fieldName);
if (fieldType.equals(String.class)) DATABASE_CMD += fieldName + " text" + ")";
else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) DATABASE_CMD += fieldName + " integer" + ")";
} else {
Logger.d("... field at " + (i+1) + "named " + fieldName);
if (fieldType.equals(String.class)) DATABASE_CMD += fieldName + " text" + ",";
else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) DATABASE_CMD += fieldName + " integer" + ",";
}
i++;
}
/**
* fixes fieldCount is not as same as the defined
*/
StringBuilder stringBuilder = new StringBuilder(DATABASE_CMD);
stringBuilder.setCharAt(stringBuilder.lastIndexOf(","), ')');
DATABASE_CMD = stringBuilder.toString();
Log.d("[DEBUG]", "... now sql cmd is " + DATABASE_CMD);
Logger.d("... now sql cmd is " + DATABASE_CMD);
}
Any comment is welcome and happy coding.
精彩评论