How do I set property value of a bean?

The Commons BeanUtils component provides a class called PropertyUtils that supplies method for manipulating a bean such as our Track class below. For this demo we use a Track class that have a property called id, title and duration.

To set the value of a bean we can use the PropertyUtils.setProperty() method. This method ask for the bean instance whose property value to be set, the property name and the value.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

public class PropertySetExample {
    public static void main(String[] args) {
        Track track = new Track();
        try {
            PropertyUtils.setProperty(track, "id", 10L);
            PropertyUtils.setProperty(track, "title", "Hey Jude");
            PropertyUtils.setProperty(track, "duration", 180);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Track = " + track);
    }
}

Some exceptions could be thrown by this method, so we need to handle the IllegalAccessException, InvocationAccessException and NoSuchMethodException. To make the code simple we will just catch it as java.lang.Exception.

These exception could happen if we don’t have access to the property, or the bean’s accessor throws an exception or if the method we tried to manipulate doesn’t exist.

How do I determine bean’s property type?

Using the PropertyUtils.getPropertyType() we can determine the bean property type. This method return a Class object of bean’s property type.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

public class PropertyType {
    public static void main(String[] args) {
        Recording recording = new Recording();
        recording.setTitle("Magical Mystery Tour");
        
        try {
            /*
             * Using PropertyUtils.getPropertyType() to determine the type of
             * title property.
             */
            Class type = PropertyUtils.getPropertyType(recording, "title");
            System.out.println("type = " + type.getName());
            
            String value = (String) PropertyUtils.getProperty(recording, "title");
            System.out.println("value = " + value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}