Search code examples
javahibernatejavabeanstablemodel

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.


Solution

  • 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++;
    }