Java如何设置bean的映射属性值?
本示例演示如何使用PropertyUtils.setMappedProperty()方法修改Mapbean的类型化属性值。要设置属性,我们需要将bean实例,属性名称,映射键和映射值传递给PropertyUtils.setMappedProperty()方法。
package org.nhooo.example.commons.beanutils; import org.apache.commons.beanutils.PropertyUtils; import java.util.HashMap; import java.util.Map; public class PropertySetMappedExample { public static void main(String[] args) { //创建Recordingbean的实例。 Recording recording = new Recording(); recording.setId(1L); recording.setTitle("Introduction"); //创建映射以保存记录轨道。 Map<String, Track> tracks = new HashMap<>(); tracks.put("track-one", new Track()); tracks.put("track-two", new Track()); tracks.put("track-three", new Track()); recording.setMapTracks(tracks); try { //我们使用添加另一个轨道到录音轨道 //一个PropertyUtils.setMappedProperty()方法。 PropertyUtils.setMappedProperty(recording, "mapTracks", "track-four", new Track()); PropertyUtils.setMappedProperty(recording, "mapTracks", "track-five", new Track()); } catch (Exception e) { e.printStackTrace(); } tracks = recording.getMapTracks(); System.out.println("New Track Numbers: " + tracks.size()); for (String key : tracks.keySet()) { System.out.println(key + " = " + tracks.get(key)); } } }
Maven依赖
<!-- 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>