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<String, Track> 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<Track> tracks = new ArrayList<>();
private Map<String, Track> 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<Track> getTracks() {
return tracks;
}
public void setTracks(List<Track> tracks) {
this.tracks = tracks;
}
public void setMapTracks(Map<String, Track> mapTracks) {
this.mapTracks = mapTracks;
}
public Map<String, Track> getMapTracks() {
return mapTracks;
}
}
And here is the result of our program.
track.getTitle() = I Saw Her Standing There
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=commons-beanutils/commons-beanutils/1.9.3/commons-beanutils-1.9.3.jar -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019