polmarex
polmarex

Reputation: 1383

Object array from Java Bean fields

Is there any way to obtain Object array of Java Bean fields? I have some bean classes that represent database tables (Hibernate) and I need to retrieve from them Object arrays for jtable model, but it seems that the only way to do this is by calling getXXX methods for each field of each class - a lot of work to do.

Upvotes: 1

Views: 2664

Answers (2)

Mudassir Shahzad
Mudassir Shahzad

Reputation: 562

The way i do it is use a "controller" class which handles all the communication between the model and the database.

You make List of the "objects" like for example private List myList = null; Now, write a generic method in the controller class. say getList which returns the list. You pass the relative class to the method and it returns you the list using the hibernate session. In your bean, do this

myList = myController.getList(YourBean.class);

And this should be your getlist method.

public List getList(Class c) throws BaseExceptionHandler {
        Session session = null;
        Transaction tx = null;
        String query = null;
        List list = null;
        try {
            query = getStringQuery(c);
            if (query != null) {
                session = sessFactory.openSession();
                tx = session.beginTransaction();
                list = (List) session.createQuery(query).list();
                tx.commit();
            }
        } finally {
            if (session != null) {
                session.close();
            }

        }
        return list;
    }

CHEERS :)

Upvotes: 0

Benoit Courtine
Benoit Courtine

Reputation: 7064

If you want a generic way to extract values from a bean, you should look at introspection (package "java.lang.reflect").

Here is a basic example:

Field[] fields = ABeanClass.getDeclaredFields();

Object[] values = new Object[fields.length];

int i = 0;

for (Field field : fields) {
    values[i] = field.get(beanInstance);
    i++;
}

Upvotes: 5

Related Questions