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 Record
object that consist of Track
objects.
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 ReadMapProperty {
public static void main(String[] args) {
Record record = new Record();
record.setTitle("Abbey Road");
Track track1 = new Track();
track1.setTitle("Come Together");
Track track2 = new Track();
track2.setTitle("Something");
Map<String, Track> tracks = new HashMap<>();
tracks.put("1", track1);
tracks.put("2", track2);
record.setMapTracks(tracks);
try {
Track track = (Track) PropertyUtils.getMappedProperty(record, "mapTracks(1)");
System.out.println("track.getTitle() = " + track.getTitle());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package org.kodejava.commons.beanutils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Record {
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() = Come Together
Maven Dependencies
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024