How do I 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 org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;
import org.kodejava.commons.beanutils.support.Record;

import java.util.HashMap;
import java.util.Map;

public class PropertySetMappedExample {

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

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

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

        tracks = record.getMapTracks();
        System.out.println("New Track Numbers: " + tracks.size());
        for (String key : tracks.keySet()) {
            System.out.println(key + " = " + tracks.get(key));
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.