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>
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