How do I set mapped property value of a bean?

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

This example demonstrate how to use PropertyUtils.setMappedProperty() method to modify a Map typed property value of a bean. To set the property we need to pass bean instance, property name, map key and map value to PropertyUtils.setMappedProperty() method.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.InvocationTargetException;

public class PropertySetMappedExample {

    public static void main(String[] args) {
        //
        // Create an instance of Recording bean.
        //
        Recording recording = new Recording();
        recording.setId(Long.valueOf(1));
        recording.setTitle("Introduction");

        //
        // Create a map to hold recording tracks.
        //
        Map<String, Track> tracks = new HashMap<String, Track>();
        tracks.put("track-one", new Track());
        tracks.put("track-two", new Track());
        tracks.put("track-three", new Track());
        recording.setTracks(tracks);

        try {
            //
            // We add another tracks to the recording track using
            // a PropertyUtils.setMappedProperty() method.
            //
            PropertyUtils.setMappedProperty(recording, "tracks",
                    "track-four", new Track());
            PropertyUtils.setMappedProperty(recording, "tracks",
                    "track-five", new Track());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        tracks = (Map<String, Track>) recording.getTracks();
        System.out.println("New Track Numbers: " + tracks.size());
    }
}
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