Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of attributes in a java class?

Tags:

java

class

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.

like image 960
llm Avatar asked Apr 21 '10 18:04

llm


People also ask

What are the attributes of a class in Java?

Java Classes can have some fields and methods that represent the individual properties and behavior/actions of the class. The fields also known as class attributes are nothing but the variables declared within the class. For instance, the Student is a class then the student's roll no, name, section, etc.

What are the attributes of an object in Java?

import java. awt. Rectangle; Rectangle objects are similar to points, but they have four attributes: x , y , width , and height .


2 Answers

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.

like image 88
BalusC Avatar answered Oct 02 '22 05:10

BalusC


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;
}
like image 32
Black Eagle Avatar answered Oct 03 '22 05:10

Black Eagle