Java如何读取索引bean的属性值?

在此示例中,您将看到如何读取诸如List或的对象的索引属性array。使用该PropertyUtils.getIndexedProperty()方法,我们可以轻松做到。此方法使用bean和包含要读取的元素的索引属性的名称。让我们看下面的示例以获取更多详细信息。

package org.nhooo.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

import java.util.ArrayList;
import java.util.List;

public class ReadIndexedProperty {
    public static void main(String[] args) {
        Recording recording = new Recording();
        recording.setId(1L);
        recording.setTitle("With The Beatles");

        List<Track> tracks = new ArrayList<>();
        Track track1 = new Track();
        track1.setTitle("It Won't Be Long");

        Track track2 = new Track();
        track2.setTitle("All I've Got To Do");

        Track track3 = new Track();
        track3.setTitle("All My Loving");

        tracks.add(track1);
        tracks.add(track2);
        tracks.add(track3);

        recording.setTracks(tracks);

        try {
            Track trackOne = (Track) PropertyUtils.getIndexedProperty(recording, "tracks[0]");
            Track trackThree = (Track) PropertyUtils.getIndexedProperty(recording, "tracks[2]");

            System.out.println("trackOne.getTitle() = " + trackOne.getTitle());
            System.out.println("trackThree.getTitle() = " + trackThree.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.nhooo.example.commons.beanutils;

import java.util.ArrayList;
import java.util.List;

public class Recording {
    private Long id;
    private String title;
    private List<Track> tracks = new ArrayList<>();

    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 getTracks() {
        return tracks;
    }

    public void setTracks(List<Track> tracks) {
        this.tracks = tracks;
    }
}

我们的计划结果是:

trackOne.getTitle() = It Won't Be Long
trackThree.getTitle() = All My Loving

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>