java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.commons.beanutils;

import java.util.HashMap;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;

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 com.javacoderanch.example.commons.beanutils;

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

public class Recording {
    private Integer id;
    private String title;
    private Map mapTracks = new HashMap();

    public Integer getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

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

    public Map getMapTracks() {
        return mapTracks;
    }

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


And here is the result of our program.

track.getTitle() = I Saw Her Standing There