How do I read indexed bean’s property value?

In this example you’ll see how to read an indexed property of an object such as List or array. Using the PropertyUtils.getIndexedProperty() method we can do it easily. This method take the bean and the name of indexed property including the element to be read. Let’s see the example below for more details.

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.ArrayList;
import java.util.List;

public class ReadIndexedProperty {
    public static void main(String[] args) {
        Record record = new Record();
        record.setId(1L);
        record.setTitle("Sgt. Pepper's Lonely Hearts Club Band");

        List<Track> tracks = new ArrayList<>();
        Track track1 = new Track();
        track1.setTitle("Sgt. Pepper's Lonely Hearts Club Band");

        Track track2 = new Track();
        track2.setTitle("With A Little Help From My Friends");

        Track track3 = new Track();
        track3.setTitle("Lucy In The Sky With Diamonds");

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

        record.setTracks(tracks);

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

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

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

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

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

Our program results are:

trackOne.getTitle() = Sgt. Pepper's Lonely Hearts Club Band
trackThree.getTitle() = Lucy In The Sky With Diamonds

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=commons-beanutils/commons-beanutils/1.9.4/commons-beanutils-1.9.4.jar -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.