java 如何获取java类中的属性数量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2685404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get number of attributes in a java class?
提问by llm
I have a java class containing all the columns of a database table as attributes (member variables) and corresponding getters and setters.
我有一个 java 类,其中包含数据库表的所有列作为属性(成员变量)和相应的 getter 和 setter。
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.
我想在这个类中调用一个方法getColumnCount()来返回列数(即类中的属性数)?如果没有对数字进行硬编码,我将如何实现?我对一般性的批评和建议持开放态度。谢谢。
回答by BalusC
Check the reflection API. If the class in question is actually a pureJavabean, you can get the number of fields (properties or columns as you call it) as follows:
检查反射 API。如果有问题的类实际上是一个纯Javabean,您可以按如下方式获取字段(属性或列)的数量:
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.
然而,我强烈质疑这样做的必要性。如果您详细说明您认为需要此方法/解决方案的功能需求,那么我们可能会建议更好的方法。
回答by maerics
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.+$".
一种方法是使用反射来列出类的方法并计算名称与正则表达式“ ^set.+$”匹配的方法。
回答by Black Eagle
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.
做一个像“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;
}
回答by u4292371
I used to have the same purpose as yours, then made a function powered by Java reflection for solving that.
我曾经和你有同样的目的,然后做了一个由 Java 反射驱动的函数来解决这个问题。
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.
欢迎任何评论和快乐编码。

