How to get number of attributes in a java class?

2019-02-21 19:18发布

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.

标签: java class
4条回答
爷、活的狠高调
2楼-- · 2019-02-21 19:38

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.

查看更多
乱世女痞
3楼-- · 2019-02-21 19:46

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.+$".

查看更多
孤傲高冷的网名
4楼-- · 2019-02-21 19:57

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;
}
查看更多
Viruses.
5楼-- · 2019-02-21 19:58

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.

查看更多
登录 后发表回答