Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the list of all attributes of a Java object using BeanUtils introspection?

I have method which gets a POJO as it's parameter. Now I want to programmatically get all the attributes of the POJO (because my code may not know what are all the attributes in it at run time) and need to get the values for the attributes also. Finally I'll form a string representation of the POJO.

I could use ToStringBuilder, but I want build my output string in certain format specific to my requirement.

Is it possible to do so in Beanutils !? If yes, any pointers to the method name? If no, should I write my own reflection code?

like image 332
Veera Avatar asked Jun 24 '09 13:06

Veera


2 Answers

I know this is a year old question, but I think it can be useful for others.

I have found a partial solution using this LOC

Field [] attributes =  MyBeanClass.class.getDeclaredFields();

Here is a working example:

import java.lang.reflect.Field;

import org.apache.commons.beanutils.PropertyUtils;

public class ObjectWithSomeProperties {

    private String firstProperty;

    private String secondProperty;


    public String getFirstProperty() {
        return firstProperty;
    }

    public void setFirstProperty(String firstProperty) {
        this.firstProperty = firstProperty;
    }

    public String getSecondProperty() {
        return secondProperty;
    }

    public void setSecondProperty(String secondProperty) {
        this.secondProperty = secondProperty;
    }

    public static void main(String[] args) {

        ObjectWithSomeProperties object = new ObjectWithSomeProperties();

        // Load all fields in the class (private included)
        Field [] attributes =  object.getClass().getDeclaredFields();

        for (Field field : attributes) {
            // Dynamically read Attribute Name
            System.out.println("ATTRIBUTE NAME: " + field.getName());

            try {
                // Dynamically set Attribute Value
                PropertyUtils.setSimpleProperty(object, field.getName(), "A VALUE");
                System.out.println("ATTRIBUTE VALUE: " + PropertyUtils.getSimpleProperty(object, field.getName()));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
like image 91
Jorge Palacio Avatar answered Oct 28 '22 18:10

Jorge Palacio


Have you tried ReflectionToStringBuilder? It looks like is should do what you describe.

like image 31
John Meagher Avatar answered Oct 28 '22 19:10

John Meagher