java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to set mapped property value of a bean?

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 com.javacoderanch.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());
    }
}