Java如何读取映射bean的属性值?

在此示例中,您将看到如何读取Bean的映射属性值。我们使用PropertyUtils.getMappedProperty()方法读取Recording由Track对象组成的对象的映射属性。

package org.nhooo.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.nhooo.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;
    }
}

这是我们程序的结果。

track.getTitle() = I Saw Her Standing There

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>