How do I set property value of a bean?

Category: commons.beanutils, viewed: 1426 time(s).

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 whos property value to be set, the property name and the value.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

import java.lang.reflect.InvocationTargetException;

public class PropertySetExample {
    public static void main(String[] args) {
        Track track = new Track();

        try {
            PropertyUtils.setProperty(track, "id", Long.valueOf(10));
            PropertyUtils.setProperty(track, "title", "Hey Jude");
            PropertyUtils.setProperty(track, "duration", Integer.valueOf(180));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException 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. This 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.

Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats