How do I read mapped bean’s property value?

In this example you’ll see how to read mapped property value of a bean. We use PropertyUtils.getMappedProperty() method the read the mapped property of the Recording object that consist of Track objects.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

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

public class ReadMapProperty {
    public static void main(String[] args) {
        Recording recording = new Recording();
        recording.setTitle("Please Please Me");

        Track track1 = new Track();
        track1.setTitle("I Saw Her Standing There");

        Track track2 = new Track();
        track2.setTitle("Misery");

        Map tracks = new HashMap<>();
        tracks.put("Track One", track1);
        tracks.put("Track Two", track2);

        recording.setMapTracks(tracks);

        try {
            Track track = (Track) PropertyUtils.getMappedProperty(recording, "mapTracks(Track One)");
            System.out.println("track.getTitle() = " + track.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.example.commons.beanutils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Recording {
    private Long id;
    private String title;
    private List tracks = new ArrayList<>();
    private Map mapTracks = new HashMap<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List getTracks() {
        return tracks;
    }

    public void setTracks(List tracks) {
        this.tracks = tracks;
    }

    public void setMapTracks(Map mapTracks) {
        this.mapTracks = mapTracks;
    }

    public Map getMapTracks() {
        return mapTracks;
    }
}

And here is the result of our program.

track.getTitle() = I Saw Her Standing There

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply