AodhanOL
AodhanOL

Reputation: 630

Is there an abstract way to get all properties of an entity in java?

I am using Netbeans 7.2.1 on windows 7.

I am trying to get all the properties of an entity and store them in a String array. I want to do this in the most general way I can think of, so a method like the one in jCSV:

public void writeAll(List<E> data) throws IOException {
    for (E e : data) {
        write(e);
    }
}

You can find that package here: https://code.google.com/p/jcsv/

public String[] getProperties( E e ){

    String [] properties = new String[ e.numberOfProperties ];
    int i = -1;

    for ( P p : e ) {

        i += 1;
        properties[i] = p.toString(); // OR properties[i] = e.getProperty[i].toString();

    }

    return properties;
}

I feel like there should be some way of doing this with the Properties class but I can't figure out a way to use it to get properties from an entity. I think it's just something simple, but I can't see where.

Upvotes: 1

Views: 2403

Answers (1)

nattyddubbs
nattyddubbs

Reputation: 2095

As @Ian Roberts alluded to check out the java Introspector class here. The class is only useful if you are using standard Java beans naming conventions for accessing the properties of your entity.

What you'll want to do is get the BeanInfo of the class using the Introspector#getBeanInfo(Class beanClass) method then use the getMethodDescriptors() method of the BeanInfo to retrieve all of the "getter" methods of the bean. From there you can iterate over them and get the properties of your entity and call toString() on them.

One of the advantages of using this class as opposed to just using plain old reflection is that it caches the BeanInfo of the class after it has introspected on it allowing for a performance gain. You also do not have to hardcode anything like get or set in your reflective code.

Here's an example of what your getProperties method would look like using the introspector:

public <T> String[] getProperties(T entity){
    String[] properties = null;
    try {
        BeanInfo entityInfo = Introspector.getBeanInfo(entity.getClass());
        PropertyDescriptor[] propertyDescriptors = entityInfo.getPropertyDescriptors();
        properties = new String[propertyDescriptors.length];
        for(int i = 0 ; i < propertyDescriptors.length ; i++){
            Object propertyValue = propertyDescriptors[i].getReadMethod().invoke(entity);
            if(propertyValue != null){
                properties[i] = propertyValue.toString();
            } else {
                properties[i] = null;
            }
        }
    } catch (Exception e){
        //Handle your exception here.
    }
    return properties;
}

This example compiles and runs.

Keep in mind Apache Commons also has a library BeanUtils which can be very helpful with things like this as well specifically (Javadoc here).

Upvotes: 1

Related Questions