1

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.

1
  • Have you tried writing your own method for this. I think you can write generic method and get all your entities from one method call. Commented Apr 7, 2012 at 20:03

2 Answers 2

5

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++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

No time to try yet, but seems like a good solution. I will answer when I try this.
0

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 :)

1 Comment

I think that you might misunderstood my question. I want to get object array of fields of bean, not object array of objects returned by hibernate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.