如何获取一个java类中的属性数? [英] How to get number of attributes in a java class?
问题描述
我有一个包含数据库表所有列的java类作为属性(成员变量)和相应的getter和setter。
I have a java class containing all the columns of a database table as attributes (member variables) and corresponding getters and setters.
我想有一个方法这个类叫做 getColumnCount()
,返回列数(即类中的属性数)?我怎么实现这个没有硬编码的数字?我对这一般的建议和建议开放。感谢。
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.
推荐答案
检查 reflection API 。如果相关类别实际上是一个纯 Javabean,则可以按如下方式获取字段数(属性或列):
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.
这篇关于如何获取一个java类中的属性数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!